Blog>
Snippets

Error Boundary for Specific Component Trees

Use multiple Error Boundaries to protect different parts of the application and provide specific error handling strategies.
class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {
    // Update state so next render will show fallback UI
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo) {
    // Log the error to an error reporting service
    logErrorToMyService(error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      // You can render any custom fallback UI
      return <h1>Something went wrong.</h1>;
    }
    return this.props.children;
  }
}
This is an ErrorBoundary component that catches JavaScript errors anywhere in its child component tree, logs the error, and displays a fallback UI instead of the component tree that crashed. Use it to wrap any part of the application.
function MyWidget() {
  // This component is one of the many that might throw an error
  if (Math.random() > 0.5) {
    throw new Error('Widget Error!'); // Simulating an error
  }
  return <div>Widget is working fine!</div>;
}
This is a functional component named MyWidget that simulates a component that may throw an error during rendering, to demonstrate how the ErrorBoundary works.
function MyApp() {
  return (
    <div>
      <ErrorBoundary>
        <MyWidget />
      </ErrorBoundary>
      <ErrorBoundary>
        <AnotherComponent />
      </ErrorBoundary>
    </div>
  );
}
This is the main component of the application. It uses the ErrorBoundary component to wrap different child components (here MyWidget and AnotherComponent are examples) separately. In case either MyWidget or AnotherComponent throws an error, it will be caught by their respective ErrorBoundary, providing isolation of error handling.
function logErrorToMyService(error, errorInfo) {
  // Replace this with your error reporting code
  console.error('Error caught by ErrorBoundary:', error, errorInfo);
}
This function serves as an example for how to log errors to an error reporting service. Replace this code with actual integration of an error reporting service like Sentry, LogRocket, or your own custom service.