React.js component lifecycle error handling phase

React JSJavascript LibraryFront End Technology

There are two main methods in error handling. These method are used in the error boundary mechanism in React. We wrap the component ( from where there is a possibility of error occurrences ) in a class which handles the below methods.

  • Static method getDerivedStateFromError(error)
  • componentDidCatch(error,info)

Static getDerivedStateFromError(error): As name of the method suggest, we can update state object here based on error received from descended component.

componentDidCatch(error, info): we can log the errors using api call. This is helpful in displaying useful error message on screen instead of technical errors.

A class can be termed as an error boundary if it implements at least one method from above two error handling lifecycle methods. Its main purpose is to show a fallback ui once we get an error.

If error is not cached by error boundary class then the entire react component tree below that component will be removed.

We can use the try catch in some methods but in application wide using error boundary is better standard. It keeps the declarative nature of react intact.

Please note − Error boundary feature works in production mode. In development mode it will display the actual errors directly on browser.

raja
Published on 04-Sep-2019 12:56:01
Advertisements