Skip to content

Error handling #182

siergieyk edited this page Mar 13, 2020 · 4 revisions

Error Handling

This feature uses 2 components:

  • ErrorBoundary.js
  • ErrorReportingTool.js

Before React 16, JavaScript errors inside components used to corrupt React’s internal state and cause it to emit cryptic errors on the next renders. These errors were always caused by an earlier error in the application code, but React did not provide a way to handle them gracefully in components, and could not recover from them.

Error boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the component tree that crashed. Error boundaries catch errors during rendering, in lifecycle methods, and constructors of the whole tree below them.

A component becomes an error boundary if it defines the componentDidCatch(error, info) method. This lifecycle method was introduced in React 16 too.

Using An Error Boundary

The error boundary is used like a normal component and is wrapped around the TodoList component. If there's ever an error in this component or its children components, the error boundary component displays a fallback UI.

Using componentDidCatch()

The componentDidCatch method works like the Javascript catch{} block, but for components. The componentDidCatch has two parameters, error and info.

  • Error: The actual error is thrown.
  • Info: It is an object with a componentStack property containing the component stack trace information.

References:

https://dev.to/sarah_chima/error-boundaries-in-react-3eib https://www.daptontechnologies.com/react-error-boundary/ https://medium.com/@leonardobrunolima/react-tips-error-handling-d6ca2171dd46 https://reactjs.org/blog/2017/07/26/error-handling-in-react-16.html

Clone this wiki locally