Blog>
Snippets

Error Boundaries with Error Reporting

Illustrate the use of error boundaries in React for capturing errors in the UI, logging them, and showing a graceful fallback UI.
class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false, errorInfo: null };
  }

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

  componentDidCatch(error, errorInfo) {
    // You can also log the error to an error reporting service
    logErrorToMyService(error, errorInfo);
    this.setState({ 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 a React component called ErrorBoundary that catches JavaScript errors anywhere in its child component tree, logs those errors, and displays a fallback UI instead of the component tree that crashed. componentDidCatch is used to log errors.
function logErrorToMyService(error, errorInfo) {
  // Send error report to an error-reporting service
  console.error('Logging error:', error, errorInfo);
  // Replace with your error reporting logic, e.g. integration with external services
}
This is a function to send error reports to an error-reporting service. Replace the console.error with your actual error reporting logic.
function MyComponent() {
  return (
    <div>
      <h1>My App</h1>
      <ErrorBoundary>
        <MyWidget />
      </ErrorBoundary>
    </div>
  );
}

function MyWidget() {
  // This will throw an error when rendered!
  throw new Error('I crashed!');
}
This function represents a React component that nests a widget inside an ErrorBoundary. If MyWidget throws an error, ErrorBoundary will catch it and display a fallback UI.
.errorBoundaryFallback {
  color: red;
  font-size: 20px;
  padding: 15px;
}
CSS styles for the ErrorBoundary fallback UI, giving it a red color and larger font size for better visibility.