How to catch uncaught errors in React ErrorBoundary

4.7k Views Asked by At

I have been using react.lizy alongside ErrorBoundary but there's a weird case I want to solve, whenever I have an error that ErrorBoundary catches and I handle the UI there's a logged "uncaught error" in the console!

My example follows a similar structure to this:

...
const LazyComponent = React.lazy(() => import(`../components/test.js`));
...
return (
   <ErrorBoundary>
       <LazyComponent />
   </ErrorBoundary>
);

In my errorBoundary I have tried both getDerivedStateFromError and componentDidCatch:

componentDidCatch(error) {
    this.setState({
        hasError: true,
        errorStack: (error && error.stack) || '',
     });
     // eslint-disable-next-line no-console
     console.log(error);
}

I know that my import will fail because the file does not exist, and that triggers the componentDidCatch function and I can update the UI, but what I'm having trouble with is the uncaught error in the console, something like this:

First one:

The above error occurred in one of your React components: at Lazy ... etc ... React will try to recreate this component tree from scratch using the error boundary you provided, ErrorBoundary

Second error:

Uncaught Error: Cannot find module './test/components/test.js'

Both these errors are expected, but they show in the console, I want to catch them and hide some of them, how can I do that using error boundary or something else?

Thanks in advance.

1

There are 1 best solutions below

2
On

As far as I know, it's not currently possible to configure an error boundary to prevent React console logging. See https://github.com/facebook/react/issues/15069.

There is a (hacky) workaround suggested in that github thread, original post:

const swallowErrors = yourTestFn => {
     const error = console.error
     console.error = () => {}
     yourTestFn()
     console.error = error
}

// Then your test
it('tests something without console log' , () => {
      swallowErrors(()=>{
            const wrap = mount(<ErBoundary><Child/></ErBoundary>)
            // ... expect errors ...
      })
})