Defining Error boundaries in ReactJS

Error boundaries in reactJS

React16 comes with the idea of error boundaries. If any part of the react interface goes down/error , it should not break the whole UI.

What is error boundary in ReactJS ?
Ans : Error Boundary is a component that catch JavaScript error anywhere in the child component tree . It log those error’s. Display the error UI , instead of showing the error tree.

When does the Error boundaries catch error ?
Ans : The error boundaries catch error during rendering in life cycle methods
a)static getDerivedStateFromError()
Above method is used to render the fallback/error UI
b)componentDidCatch()
Above method is used to log error

What does Error boundaries can not catch ?
Ans : Error boundaries can not catch following entities :
a)Error boundaries do not catch error in event handler’s. If we need to catch the error in event handler then we can use regular try/catch block. Unlike the render() method and life cycle method , the event handler do not happen during rendering.
SO , error handling in event handler can be done using try-catch block


import React from ‘react’;
class EventHandle extends React.Component{

constructor(){
  super();
  this.state={
    error : null
  }
}

handleMe = ()=>{
  try{
//write code here
throw new Error(“Something wrong happened !”);
  }
  catch(err){
this.setState({
  error : err.toString()
})
  }
}

render(){
  if(this.state.error){
    return <h1>{this.state.error}</h1>
  }
  return <div>
  All is well ! <br/>
  <button onClick={this.handleMe}>Click Me</button>
  </div>
}

}

export default EventHandle;

b)Asynchronous code (setTimeout )
c)Server side rendering
d)If error got thrown in the error boundary itself and not inside the child component hirarachy

How we can create a Error Boundary?
Ans : Any class component became the Error Boundary component if it implements 2 life cycle methods
a)static getDerivedStateFromError()
b)componentDidCatch()

Code Below :

WE have created the Home.js component. Inside this component we have called the child component Image.js. Image.js component takes the path as props and display that image path in render method.
Now , if any path is empty we need to show the error without disturbing the whole UI with error stack.
For handling the error , we have defined the Error Boundaries component
Home .js

import React from ‘react’;
import Image from ‘./Image’;
import ErrorBoundary from ‘./ErrorBoundary’;
class Home extends React.Component{
render(){
  return (
    <div>
    <ErrorBoundary>
<Image path=”https://image.shutterstock.com/image-photo/roasted-coffee-beans-background-600w-727279162.jpg”/>
</ErrorBoundary>
<ErrorBoundary>
<Image path=”https://pixabay.com/images/download/winter-moutain-4910186_1920.jpg”/>
</ErrorBoundary>
<ErrorBoundary>
<Image path=””/>
</ErrorBoundary>
    </div>
  )
}
}
export default Home;
 
 
 

Image.js

import React from ‘react’;
class Image extends React.Component{
constructor(props){
  super(props);
}
render(){
  console.log(‘The path is ‘,this.props.path);
  if(this.props.path==””){
    throw new Error(“Image path not found !”);
  }
  return <img src={this.props.path} width=”250″ height=”250″/>
}
}
export default Image;
 

ErrorBoundary.js

import React from ‘react’;
class ErrorBoundary extends React.Component{
constructor(){
  this.state = {
    hasError : false,
    errMessage : “”
  }
}
componentDidCatch(err,info){
console.log(‘The error is ‘,err);
console.log(‘Additional info ‘,info);
}

static getDerivedStateFromError(error){
  console.log(‘Inside the life cycle method getDerivedStateFromError ‘);
//update the state so that the next render will be fallback/error UI
return {
  hasError : true,
  errMessage : error.toString()
}
}

render(){
  if(this.state.hasError){
    return <h2>{this.state.errMessage}</h2>
  }
  return this.props.children;
}
}

export default ErrorBoundary;

 

The output

Site Footer