Redirect to error page ReactJS and react-router

Nicolas M. Pardo picture Nicolas M. Pardo · Apr 3, 2018 · Viewed 10.2k times · Source

I'm trying to send the user to a generic error page when the App breaks, thing is I'm trying with the ErrorBoundary method and then rendering out the Redirect;

export default class ErrorBoundary extends Component {
    state = { has_error: false }

    componentDidCatch(error, info)
        this.setState({ has_error: true });
    }


    render() {
        if (this.state.has_error)
            return <Redirect to="/somewhere/else" />
        }
        return this.props.children;
    }
};

And then using the ErrorBoundary to wrap all the routes and sub components inside the Router

<Router history={history}>
    <ErrorBoundary>
        <Header />
        <Switch>
            <Route exact path="/" component={Home} />
            <Route
                path="/createManager/:managerId"
                component={CreateManager}
            />
            <Route path="/login" component={LoginComp} />
            <Route path="/test" component={Test} />
            <Route path="/register" component={RegisterAccount} />
            <Route component={NotFound} />
        </Switch>
        <Footer />
    </ErrorBoundary>
</Router>

The componentDidCatch is never triggered, thus, never leaving the current error page, neither in the dev nor prod version. How can I send the user to a X route when the App breaks or tries to throw an error?

In order to trigger an error, I leave one Component with an empty prop, and later on click trying to use the function that should be passed in the prop.

Answer

Kenneth Truong picture Kenneth Truong · Apr 4, 2018

componentDidCatch only triggers if the error is thrown inside the render method.

The reason why your componentDidCatch is not triggered is because events like onClick is not in the render lifecycle. So componentDidCatch won't be able to catch this kind of error.

One way to test out the your componentDidCatch is throwing an error inside the render method.

For errors outside of the render method you have to be careful and add try/catches in places you think might have errors in your action handlers.

Also a good way to prevent undefined onClick is to add flow or typescript.

https://reactjs.org/blog/2017/07/26/error-handling-in-react-16.html#component-stack-traces

React 16 prints all errors that occurred during rendering to the console in development, even if the application accidentally swallows them. In addition to the error message and the JavaScript stack, it also provides component stack traces. Now you can see where exactly in the component tree the failure has happened: