Home > Software engineering >  How to handle uncaughtException in react and render a simple "internal bug" message to the
How to handle uncaughtException in react and render a simple "internal bug" message to the

Time:05-25

On the node side,

// Event 'uncaughtException'
process.on('uncaughtException', (error, source) => {
   fs.writeSync(process.stderr.fd, error, source);
});

What is the equivalent of the above for the frontend with ReacT?

CodePudding user response:

The closest concept of uncoughtException in React is called "Error Boundaries":
https://reactjs.org/docs/error-boundaries.html

These elements will catch any rendering error which happen within their subtree.
Within the render method you can display some kind of "internal error" message.

CodePudding user response:

React 16 introduced error boundaries via a class component lifecycle method: componentDidCatch, however there are some caveats that you should read about in the documentation below.

componentDidCatch

/*
* Implementation
*/
class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  componentDidCatch(error, info) {
    // Display fallback UI
    this.setState({ hasError: true });
    // You can also log the error to an error reporting service
    logErrorToMyService(error, info);
  }

  render() {
    if (this.state.hasError) {
      // You can render any custom fallback UI
      return <h1>Something went wrong.</h1>;
    }
    return this.props.children;
  }
}


/*
* Usage
*/
<ErrorBoundary>
  <MyWidget />
</ErrorBoundary>

react-error-boundary

However, instead of implementing the above, I'd highly suggest using something like react-error-boundary from Brian Vaughn.

It's flexible, allows for error recovery, and doesn't outwardly rely on any React lifecycle methods.

import {ErrorBoundary} from 'react-error-boundary'

const ErrorFallback = () => <div>Something went wrong</div>

const myErrorHandler = (error: Error, info: {componentStack: string}) => {
  // Do something with the error
  // E.g. log to an error logging client here
}

const ui = (
  <ErrorBoundary FallbackComponent={ErrorFallback} one rror={myErrorHandler}>
    <ComponentThatMayError />
  </ErrorBoundary>,
)
  • Related