3

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 Answer 1

1

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 ...
      })
})
Sign up to request clarification or add additional context in comments.

2 Comments

I'm not talking about test wise, those are showing in my prod.
The technique above, of temporarily overwriting console.error, could be used in prod inside your error boundary. The test above just demonstrates the technique. It's so hacky I wouldn't, personally, but I included it for completeness. As far as I know this simply isn't supported right now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.