by Sai gowtham

How to catch the errors in react using error boundaries

In this tutorial, we are going to learn about how to catch the errors in react using error boundaries.

What is an Error boundary?

In the past, we don’t have a way to catch the errors in React components and we are seeing some cryptic errors in case our app breaks.

React 16 introduces a new way to catch errors by using the error boundaries.

Error boundaries are react components which helps us to catch the errors anywhere in our app and renders the fallback UI.

Error boundaries don’t break the whole App component tree instead of it only renders the fallback UI on an error occurred component.

Error boundaries are only defined in a class-based components.

Let’s see an example

We are using the componentDidCatch lifecycle method to update the error state and logging the errorInfo in the console.

class ErrorBoundary extends Component {
  state = {
    error: false,
    errorInfo: null
  };
  componentDidCatch(error, errorInfo) {
    this.setState({
      error: error,
      errorInfo: errorInfo
    });
  }

  render() {
    if (this.state.error) {
      return (
        <div style={{ whiteSpace: "pre" }}>
          <h2>Something went wrong</h2>
          {this.state.error && this.state.error.toString()}
          <br />
          <p>Error occured {this.state.errorInfo.componentStack}</p>
        </div>
      );
    }

    return this.props.children;
  }
}

The ErrorBoundary component only renders the fallback UI if an error has occurred otherwise we are rendering the children.

Let’s use the ErrorBoundary component to catch the errors.

function Welcome(props) {
  return <h1>{props.name}</h1>;}

function App(props) {
  return (
    <div>
      <ErrorBoundary>
        <Welcome />      </ErrorBoundary>
      <br />
      <h2>Date Component is working</h2>
      <Date />
    </div>
  );
}

In the above code, we wrapped the Welcome component with an ErrorBoundary component.

Output

react error boundaries demo

The Welcome component is rendering the fallback UI because we failed to pass a name prop and our remaining part of the app is working fine.

Where to place ErrorBoundary components?

You can use it on the top level of your app components or you can wrap it on the individual components to stop the breaking the other parts of the app.

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
130,921 students enrolled
21 hours of video content
View Course