Blog>
Snippets

Error Handling in Class Components

Use the componentDidCatch lifecycle method to show how to handle errors gracefully within class components.
class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  componentDidCatch(error, info) {
    // You can also log the error to an error reporting service
    this.setState({ hasError: true });
    console.log(error, info);
  }

  render() {
    if (this.state.hasError) {
      // You can render any custom fallback UI
      return <h1>Something went wrong.</h1>;
    }
    return this.props.children;
  }
}
This is an Error Boundary component that uses the componentDidCatch lifecycle method. The componentDidCatch method is designed to catch JavaScript errors anywhere in the child component tree, log those errors, and display a fallback UI instead of the component tree that crashed. The componentDidCatch receives two arguments: error (the error that was thrown) and info (an object with a componentStack key containing information about which component threw the error). When an error is caught, the state is updated to indicate that an error has occurred, and a graceful fallback UI is rendered.
class MyComponent extends React.Component {
  render() {
    // This code assumes that you have some logic that might throw an error
    if (/* some error condition */)
      throw new Error('I have crashed!');
    return <div>Hello, World!</div>;
  }
}
This is a React component called MyComponent which contains some code that might throw an error under certain conditions. If that error condition is met, the component throws an error, simulating a runtime exception that would be caught by an Error Boundary component higher up in the tree.
class App extends React.Component {
  render() {
    return (
      <ErrorBoundary>
        <MyComponent />
      </ErrorBoundary>
    );
  }
}
This is the App component that uses the ErrorBoundary component to wrap around the MyComponent. By wrapping MyComponent in an ErrorBoundary, we are ensuring that if MyComponent throws an error, the ErrorBoundary will catch it and display the appropriate fallback UI so that the entire application does not crash.