1 the introduction

Error Boundaries are A concept React16 developed to catch errors in rendering. Today we will read A Simple Guide to Error Boundaries in React and learn about this important mechanism.

2 an overview

Error Boundaries can be used to catch render errors, with the following API:

class MyErrorBoundary extends Component {
  state = {
    error: null};static getDerivedStateFromError(error) {
    // Update state so that the next rendering can show the error-related UI
    return { error: error };
  }

  componentDidCatch(error, info) {
    // Error reported
    logErrorToMyService(error, info);
  }

  render() {
    if (this.state.error) {
      // Render error UI
      return <p>Something broke</p>;
    }
    return this.props.children; }}Copy the code
  • static getDerivedStateFromError: Chance to change state after an error triggers rendering of the last error fallback.
  • componentDidCatch: Used for error side effect code, such as error reporting.

When either of these methods is defined, this component becomes an Error Boundary component that prevents the child component from rendering an Error.

In the end, the author also puts forward a suggestion that Error Boundary should be used as a component alone, instead of coupling the Error monitoring method with the business component. On the one hand, for reuse, on the other hand, Error detection is only effective for sub-components.

Well, the React documentation is much more detailed than this article, so that’s the end of the article.

3 intensive reading

React Error Boundaries The official document notes four types of Error scenarios that cannot be caught:

  1. Callback event. Since the execution time of the callback event is not within the rendering cycle, it cannot be caught by Error Boundary Catch. If necessary, try/ Catch by yourself.
  2. Asynchronous. Such assetTimeoutrequestAnimationFrameSame with the first rule.
  3. Server rendering.
  4. Error Boundary Indicates an Error triggered by the component itself. Because you can only catch errors in its children.

This is where Error Boundaries are most problematic. In addition to the above, the author lists several abnormal boundary scenarios based on his own experience.

Unable to catch compile-time errors

It is clear that even the React official API Error Boundary can only catch run-time errors, not compile-time errors.

Compile-time errors include but not limited to compilation environment errors, pre-run frame Error checking prompt, TS/Flow type errors, etc., which cannot be caught by Error Boundary and there is no better way to Catch them. If you encounter compilation errors, just focus on runtime errors.

Can be applied to Function Component

Although the functional component cannot define Error Boundary, Error Boundary can capture the Error of the functional component, so it can save the country by curve:

/ / ErrorBoundary components
class ErrorBoundary extends React.Component {
  // ...
}

// Can catch all Component exceptions, including children of Function Component
const App = (a)= > {
  return (
    <ErrorBoundary>
      <Child />
    </ErrorBoundary>
  );
};
Copy the code

This also works for Hooks

Exceptions from Hooks also work, as in the following code:

const Child = (props) = > {
  React.useEffect((a)= > {
    console.log(1);
    props.a.b;
    console.log(2);
  }, [props.a.b]);

  return <div />;
};
Copy the code

Note that errors that occur in DEPS are immediately caught, causing console.log(1) to fail to print. Console.log (1) can be printed, but console.log(2) cannot:

const Child = (props) = > {
  React.useEffect((a)= > {
    console.log(1);
    props.a.b;
    console.log(2); } []);return <div />;
};
Copy the code

Error Boundary cannot be specified by Hooks and has no effect on function:

componentDidCatch and getDerivedStateFromError: There are no Hook equivalents for these methods yet, but they will be added soon.

React-hooks FQA has a treasure trove of Hooks. Take the time to read them.

4 summarizes

Error Boundary can catch all child render exceptions, including render and various life cycle functions, but it has many limitations so I hope you can use it correctly.

Error capture is not a panacea. More often, we should avoid and fix errors in time, reduce the impact of errors on user experience through error capture, and monitor them in the first time and quickly repair them.

Finally, do you have any wrong Case that you couldn’t Catch even though you clearly used Error Boundary correctly?

The discussion address is: Close read React Error Boundaries · Issue #246 · dt-fe/weekly

If you’d like to participate in the discussion, pleaseClick here to, with a new theme every week, released on weekends or Mondays. Front end Intensive Reading – Helps you filter the right content.

Pay attention to the front end of intensive reading wechat public account

Copyright Notice: Freely reproduced – Non-commercial – Non-derivative – Remain signed (Creative Commons 3.0 License)