React error boundary (What You Should Know & How to Solve)

  1. What is the error boundary?

Error boundary is a kind of react component. This component can capture JavaScript errors anywhere in its sub component tree, print these errors, and display the degraded UI , without rendering those sub-component trees that crash. Error boundaries catch errors during rendering, in the lifecycle method, and in the constructor of the entire component tree.

Note: the error boundary cannot capture the errors generated in the following scenarios

    event handling asynchronous code (such as setTimeout or requestanimationframe callback function) the server renders the errors thrown by itself (not its sub components)

If anyone (or both) of the two lifecycle methods static getderivedstatefromerror() or componentdidcatch() is defined in a class component, it becomes an error boundary. When an error is thrown, please use static getderivedstatefromerror() to render the alternate UI and componentdidcatch() to print the error message.

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

  static getDerivedStateFromError(error) {
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo) {
    logErrorToMyService(error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      return <h1>Something went wrong.</h1>;
    }

    return this.props.children; 
  }
}

You can then use it as a regular component:

<ErrorBoundary>
  <MyWidget />
</ErrorBoundary>

The working mode of the error boundary is similar to the catch {} of JavaScript, except that the error boundary is only for the react component. Only the class component can be an error boundary component. In most cases, you only need to declare the error boundary component once and use it throughout the application.

Note that the error boundary can only catch the errors of its subcomponents, it cannot catch its own errors. If an error boundary cannot render the error message, the error will bubble to the nearest upper error boundary, which is also similar to the working mechanism of catch {} in JavaScript.

2. React error boundary

https://github.com/bvaughn/react-error-boundary
https://www.npmjs.com/package/react-error-boundary
The above address is the error boundary wheel encapsulated by the boss, which can be used directly. Please check the relevant documents for details

Read More: