Error Handling In React-JS

First of all, create a new project

npx create-react-app error-handling

Then make a wrapper component  (make sure the wrapper component should be a class component)

you can make an error boundary component using the following two methods:-

  1. static getDerivedStateFromError
  2. componentDidCatch
import React from "react";

export default class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      error: null,
      errorInfo: null,
    };
  }

  componentDidCatch(error, errorInfo) {
    // Catch errors in any child components and re-renders with an error message
    this.setState({
      error: error,
      errorInfo: errorInfo,
    });
  }
  render() {
    if (this.state.error) {
      // Fallback UI if an error occurs
      return (
        <div>
          <h2>{"Oh-no! Something went wrong"}</h2>
          <p className="red">
            {this.state.error && this.state.error.toString()}
          </p>
          <div>{"Component Stack Error Details: "}</div>
          <p className="red">{this.state.errorInfo.componentStack}</p>
        </div>
      );
    }
    // component normally just renders children
    return this.props.children;
  }
}

ErrorBoundary catches all the errors in the component which are wrapped inside it and occurs in the render phase.

Example:

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories