Error handling in ReactJS with Error Boundary

Tram Ho

Hello everyone, today I would like to introduce a concept in ReactJS, which is Error Boundary.

What is Error Boundary?

Previously when there was an error in a component , ReactJS would return confusing errors on subsequent renderings, causing errors for the entire application, which makes it difficult to fix and recover from bugs. Since version 16 , ReactJS brings a new concept of Error Boundary , which is a component supports error handling.

Error Boundary does what?

If you have ever used the try ... catch block, then you can understand that Error Boundary has similar features, but instead of applying it to a piece of code, it will apply to the component .

Error Boundary will catch the errors of all child components, print out the errors, and display a fallback UI (a redundant display part).

Error Boundary catches errors during render , in lifecycle functions, and in the constructors of all the component below it (as long as in the same component tree ).

Error Boundary how to use?

You can only create 1 Error Boundary by 1 Class component .

A Class component becomes an Error Boundary if it defines one or both of the following functions

This function is used to render a fallback UI if an error is returned.

This function is used to capture and log or display errors.

Once your component has both of these functions, you’ll wrap it around another component to use the Error Boundary feature.

For example

And in the index.js file

I would like to explain this example as follows:

You have an App component, the render of this component is wrapped around an Error Boundary . This component has 1 button that when pressed 3 times it will return an error. And instead of the white screen as always, Error Boundary will catch the internal component error and render <h1>Some thing went wrong</h1>

Where should Error Boundary be located?

This is up to the writer, can be placed at the top layer of the application to catch all errors, also set deeper to catch errors for specific.

Error Boundary Limits

Error Boundary could not catch the error

  • Event Handler
  • Functions that run asynchronously ( setTimeout or requestAnimationFrame )
  • Server side render
  • Error is emanating from itself
  • The error of the components is above it
  • The component’s error is 8000 miles from its component tree

Hopefully after this article you have 1 useful tool to help debug ReactJs application. You can read more here . Thanks for reading.

Share the news now

Source : Viblo