Lesson 12-React Error Handling and Exception Management

React Error Boundaries

React Error Boundaries are React components that catch JavaScript errors occurring anywhere in their child component tree, log those errors, and render a fallback UI instead of the crashed component tree. Error boundaries catch errors during rendering, in lifecycle methods, or in constructors.

Defining Error Boundaries

Error boundaries must be class components and implement at least one of the following lifecycle methods:

  • static getDerivedStateFromError(error): Called after an error is thrown during rendering, allowing the component to render a fallback UI in subsequent renders.
  • componentDidCatch(error, errorInfo): Called after an error is thrown during rendering, lifecycle methods, or constructors, enabling error logging.

Implementing Error Boundaries

Defining an Error Boundary Component

import React from 'react';

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

  static getDerivedStateFromError(error) {
    // Update state to display fallback UI
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo) {
    // Log errors to a custom service
    logErrorToMyService(error, errorInfo);
  }

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

    return this.props.children; // Render child components normally
  }
}

export default ErrorBoundary;

Using Error Boundaries

Wrap the error boundary around the components you want to protect:

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

function App() {
  return (
    <div className="App">
      <ErrorBoundary>
        <MyWidget />
      </ErrorBoundary>
    </div>
  );
}

export default App;

Error Boundary Lifecycle

Error boundaries are activated in the following cases:

  • When a child component throws an error during rendering.
  • When a child component throws an error in lifecycle methods (e.g., componentDidMount, componentDidUpdate).
  • When a child component throws an error in its constructor.

Once an error is caught, the error boundary enters a fallback state until the component tree is updated.

Accessing and Handling Error Information

The componentDidCatch method receives two parameters: error and errorInfo. error is the thrown error object, while errorInfo contains component stack information to help identify the error source.

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

Recovering Error Boundaries

Error boundaries remain in a fallback state until the component tree is updated. You can recover error boundaries by:

  • Manually refreshing the page.
  • Re-rendering the component tree during server-side rendering (SSR) with each request.
  • Using state or props within the error boundary to control recovery logic.

Best Practices for Error Boundaries

Avoid Infinite Loops

Ensure error boundaries do not trigger infinite loops of error throwing and catching. For example, avoid setting state in componentDidCatch, as it may cause infinite re-renders.

Avoid Side Effects in getDerivedStateFromError

getDerivedStateFromError should only return a new state object and avoid side effects like logging or network requests.

Avoid Overusing Error Boundaries

Use error boundaries judiciously, wrapping only critical component trees. Overuse can make the application bulky and complicate error tracking.

React Exception Management

Error Boundaries

Error boundaries are class components in React that catch and handle JavaScript errors in their child component tree, effective during rendering, lifecycle methods, or constructors.

Defining Error Boundaries

Error boundaries must implement static getDerivedStateFromError and componentDidCatch.

import React from 'react';

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

  static getDerivedStateFromError(error) {
    // Update state to show fallback UI
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo) {
    // Log errors
    console.error('Uncaught error:', error, errorInfo);
  }

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

    return this.props.children; // Render child components
  }
}

Using Error Boundaries

Wrap error boundaries around components you want to protect.

<ErrorBoundary>
  <MyWidget />
</ErrorBoundary>

Exception Logging

In addition to logging errors in error boundaries, use professional logging services like Sentry, Rollbar, or a custom logging system.

// Example logging service
function logErrorToMyService(error, errorInfo) {
  fetch('/api/log-error', {
    method: 'POST',
    body: JSON.stringify({ error, errorInfo }),
  });
}

Error Recovery and Retry

For transient errors, implement retry mechanisms using state management libraries (e.g., Redux, MobX) or simple state.

import React, { useState } from 'react';

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

  const fetchData = async () => {
    try {
      setLoading(true);
      const response = await fetch('/api/data');
      const data = await response.json();
      setData(data);
      setError(null);
    } catch (error) {
      setError(error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div>
      {loading && <p>Loading...</p>}
      {error && <p>Error: {error.message}</p>}
      {data && <p>Data: {JSON.stringify(data)}</p>}
      <button onClick={fetchData}>Fetch Data</button>
    </div>
  );
}

Global Exception Management with React Context

Use React Context to share exception management logic across the application.

// ErrorContext.js
import React, { createContext, useContext, useState } from 'react';

const ErrorContext = createContext();

const ErrorProvider = ({ children }) => {
  const [error, setError] = useState(null);

  const handleError = (err) => {
    setError(err);
    // Add error logging logic here
  };

  return (
    <ErrorContext.Provider value={{ error, handleError }}>
      {children}
    </ErrorContext.Provider>
  );
};

export { ErrorContext, ErrorProvider };

Use ErrorProvider in the root component:

import React from 'react';
import { ErrorProvider } from './ErrorContext';

function App() {
  return (
    <ErrorProvider>
      <div className="App">
        {/* Application content */}
      </div>
    </ErrorProvider>
  );
}

Best Practices for Exception Handling

  • Use Error Boundaries: Apply error boundaries to critical component trees to prevent application crashes.
  • Log Detailed Errors: Record sufficient error details for debugging and issue tracking.
  • Provide User-Friendly Error Messages: Display clear error messages to users without exposing sensitive system information.
  • Regularly Review Error Logs: Periodically check error logs to promptly address application issues.
  • Implement Error Recovery and Retry: For recoverable errors, provide retry mechanisms to enhance user experience.

Share your love