Error boundary in React.js


The error boundary mechanism helps to show meaningful error message to user on production instead of showing any programming language error.

Create a react class component

import React, {Component} from 'react';
class ErrorBoundary extends Component{
   state={
      isErrorOccured:false,
      errorMessage:''
   }
   componentDidCatch=(error,info)=>{
      this.setState({isErrorOccured:true,errorMessage:error});
   }
   render(){
      if(this.state.isErrorOccured){
         return <p>Something went wrong</p>
      }else{
         return <div>{this.props.children}</div>
      }
   }
}
export default ErrorBoundary;

We have a state object having two variables isErrorOccured and errorMessage which will be updated to true if any error occurs.

We have used a React life cycle method componentDidCatch which receives two arguments error and info related to it.

In the render method of ErrorBoundary class we are checking if any error is set we are displaying a simple error saying ‘Something went wrong’

If no errors set we are just returning the prop children

How to use error boundary

<ErrorBoundary>
   <User/>
</ErrorBoundary>

We are wrapping the child component where there is possibility of error occurring inside error boundary like above.

Please note that this error boundary approach only works in production mode of build. In development mode it simply displays the actual error on browser instead of these custom errors.

Use of Error Boundary on production helps to show user meaningful error message on screen instead of displaying some technical code errors.

Updated on: 04-Sep-2019

219 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements