Open In App

How does React Handle Errors in the Component Tree ?

In the older versions of React (before v16), we do not have any feature to handle the React errors which were occurred in the components and these errors are used to corrupt the internal state of the React component.

Below are the methods to handle errors in the React component tree:

Using Error Boundaries

Error boundary in React is a class component that catches JavaScript errors that occur in the child component tree and displays a fallback UI instead of the component that is crashed. An error boundary is created by defining either of the life cycle methods static getDerivedStateFromError() or componentDidCatch() in the class component. You can create an error boundary component once and use it throughout the application.

NOTE: Error boundaries don't catch errors for Event handlers, Asynchronous code, Server side rendering, and Errors that occurred within the error boundary itself.

Example: The below code practically implements the error boundaries to handle errors in react component tree.

// App.js

import React from 'react';
import ErrorBoundary from 
    './errorboundary';

function BrokenComponent() {
    throw new Error
        ('Something bad happened!');
}

function App() {
    return (
        <ErrorBoundary>
            <BrokenComponent />
            <p>
                This content will be 
                displayed normally.
                </p>
        </ErrorBoundary>
    );
}

export default App;
// errorboundary.js

import React, { Component } from 'react';

export class ErrorBoundary extends 
    Component {
    constructor(props) {
        super(props);
        this.state = { hasError: false };
    }

    static getDerivedStateFromError(error) {
        return { hasError: true };
    }

    componentDidCatch(error, info) {
        console.error("Error in component:", error);
        console.error("Error info:", info);
    }

    render() {
        if (this.state.hasError) {
            return <h1>
                    Something went wrong.
                </h1>;
        }
        return this.props.children;
    }
}
export default ErrorBoundary;

Output :

ReactOP

Using Try/Catch with event Handlers

In React, error boundaries do not catch errors that occur inside event handlers, to catch such errors we use the regular JavaScript try/catch block with event handlers.

Syntax:

try {
changeButton();
}
catch (error) {
// Error Handler code
}

Example: The below code implements the try/catch block with event handlers to handle errors in react components.

// App.js

import React, { Component } from "react";

export class MyComponent extends Component {
    constructor(props) {
        super(props);
        this.state = { error: null };
        this.handleButton = this.
            handleButton.bind(this);
    }

    handleButton() {
        try {
            throw new Error
                ("Something bad happened!");
        } catch (error) {
            this.setState({ error });
            console.log(error.message)
        }
    }
    render() {
        if (this.state.error) {
            return <div>
                <h1>
                    Caught an error.
                </h1>
            </div>
        }
        return <div>
            <h2>
                Click the below button to
                <br /> catch the error.
            </h2>
            <button onClick={this.handleButton}>
                Click Me
            </button>
        </div>
    }
}
export default MyComponent;

Output:

fosiGIF

Article Tags :