</>
Skip to content
React lessons (31/47)

React — Error Handling

Error Boundaries

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

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

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

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

        return this.props.children;
    }
}

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

Try-Catch in Async Code

function DataFetcher() {
    const [data, setData] = useState(null);
    const [error, setError] = useState(null);

    useEffect(() => {
        const fetchData = async () => {
            try {
                const response = await fetch('/api/data');
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                const json = await response.json();
                setData(json);
            } catch (err) {
                setError(err.message);
            }
        };

        fetchData();
    }, []);

    if (error) return <div className="error">{error}</div>;
    if (!data) return <div>Loading...</div>;

    return <div>{JSON.stringify(data)}</div>;
}

Error Handling Examples

// Form validation errors
function Form() {
    const [errors, setErrors] = useState({});

    const validate = (data) => {
        const newErrors = {};

        if (!data.name) {
            newErrors.name = 'Name is required';
        }

        if (!data.email) {
            newErrors.email = 'Email is required';
        } else if (!/\S+@\S+\.\S+/.test(data.email)) {
            newErrors.email = 'Email is invalid';
        }

        return newErrors;
    };

    const handleSubmit = (e) => {
        e.preventDefault();
        const newErrors = validate(formData);

        if (Object.keys(newErrors).length > 0) {
            setErrors(newErrors);
            return;
        }

        // Submit form
    };

    return (
        <form onSubmit={handleSubmit}>
            <input name="name" />
            {errors.name && <span className="error">{errors.name}</span>}

            <input name="email" />
            {errors.email && <span className="error">{errors.email}</span>}

            <button type="submit">Submit</button>
        </form>
    );
}

// API error handling
function ApiComponent() {
    const [error, setError] = useState(null);
    const [retrying, setRetrying] = useState(false);

    const fetchData = async () => {
        try {
            const response = await fetch('/api/data');
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return await response.json();
        } catch (err) {
            setError(err.message);
            throw err;
        }
    };

    const handleRetry = async () => {
        setRetrying(true);
        try {
            await fetchData();
            setError(null);
        } catch (err) {
            // Error already set
        } finally {
            setRetrying(false);
        }
    };

    if (error) {
        return (
            <div>
                <p>Error: {error}</p>
                <button onClick={handleRetry} disabled={retrying}>
                    {retrying ? 'Retrying...' : 'Retry'}
                </button>
            </div>
        );
    }

    return <div>Data loaded successfully</div>;
}

Mini Practice

Write React code that:

  1. Creates an error boundary
  2. Handles async errors with try-catch
  3. Displays error messages
  4. Implements retry logic

Up Next

Next: Learn about Forms Validation.

Related Topics

Frequently Asked Questions about Error Handling

What is Error Handling in React?

Error Handling is a fundamental concept in React. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Error Handling?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Error Handling.

Why is Error Handling important in React?

Error Handling is essential for React development. Understanding this concept will help you write better code and solve real-world problems more effectively.