Skip to content
Home Tutorials Roadmaps Courses
Log in Join free
Tutorials React Error Handling
React Intermediate FREE

Error Handling

Lesson 1 of 17 Intermediate Interactive

Error boundaries catch JavaScript errors anywhere in their child component tree.

Syntax

REACT
class ErrorBoundary extends React.Component {
    state = { hasError: false };
    static getDerivedStateFromError(error) {
        return { hasError: true };
    }
    render() {
        if (this.state.hasError) return <h1>Something went wrong</h1>;
        return this.props.children;
    }
}
React Error Boundaries
REACT
import React, { Component } from "react";

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

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

    componentDidCatch(error, errorInfo) {
        console.error("Error:", error, errorInfo);
    }

    render() {
        if (this.state.hasError) {
            return <h1>Something went wrong.</h1>;
        }

        return this.props.children;
    }
}

function DangerousComponent() {
    throw new Error("Boom!");
    return <div>Never rendered</div>;
}

function App() {
    return (
        <ErrorBoundary>
            <DangerousComponent />
        </ErrorBoundary>
    );
}

export default App;
Error Boundaries
REACT
import React from "react";

class ErrorBoundary extends React.Component {
    state = { hasError: false };

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

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

function App() {
    return (
        <ErrorBoundary>
            <BuggyComponent />
        </ErrorBoundary>
    );
}