How to deal with errors in React

Best practices for handling errors in React using error boundaries

When using a component, if any error occurs within the component code, React will unload the entire React component tree and renderNo. This is the React method of handling crashes.

You don’t want the error to be shown to your users. React decides to display a blank page.

However, this is only the default setting. Showing a blank page is only better than showing a secret message to the user, but you should have a better way.

If you are in development mode, any error will trigger a detailed stack trace, printed toBrowser DevToolscomfort. But, of course not in a production environment, you don't actually want to print errors to users.

In production, you should intercept errors and display some kind of useful information to the people who use the application.

This is whereError boundaryJoin in.

With error boundaries, you can isolate parts of the application and handle errors locally.

The error boundary is a React component that implementscomponentDidCatch()Life cycle events, and package other components:

class ErrorHandler extends React.Component {
  constructor(props) {
    this.state = { errorOccurred: false }

componentDidCatch(error, info) { this.setState({ errorOccurred: true }) logErrorToMyService(error, info) }

render() { return this.state.errorOccurred ? <h1>Something went wrong!</h1> : this.props.children } }

In the component JSX, you can use it like this:

  <SomeOtherComponent />

When an internal error occursSomeOtherComponentOr other subcomponents, and the entire component subtree they have,ErrorHandlerIt will be intercepted, and you can handle the error gracefully.

In the above case, inspired by the official React documentation, we have aerrorOccurredThe state property, when set to true, will make the interface present the error handling UI, otherwise it will present the normal application UI tree.

insidecomponentDidCatch(), It receives 2 parameters describing the error, which we also calllogErrorToMyService()This is just a stub of some function, which uses services such as Sentry, Roller, Airbrake or other services that can record errors well for you to check, so you don't have to rely on the user to tell you that there is an error to pay attention to a problem.

Download mine for freeResponse Handbook

More response tutorials: