Blog>
Snippets

Improvements in Error Boundaries

Show the latest enhancements in error boundaries, such as better stack traces and error logging.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Error Boundary Example</title>
<style>
  .error-boundary {
    padding: 1em;
    background-color: #ffdede;
    border: 1px solid #ff5d5d;
    color: #900;
  }
</style>
</head>
<body>
  <div id="app"></div>

  <script type="text/babel">
    class ErrorBoundary extends React.Component {
      constructor(props) {
        super(props);
        this.state = { hasError: false, error: null, errorInfo: null };
      }

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

      componentDidCatch(error, errorInfo) {
        this.setState({ errorInfo });

        // Log error to an error reporting service here
        console.error('Caught an error:', error, errorInfo);
      }

      render() {
        if (this.state.hasError) {
          return (
            <div className="error-boundary">
              <h2>Something went wrong.</h2>
              <details style={{ whiteSpace: 'pre-wrap' }}>
                {this.state.error && this.state.error.toString()}
                <br />
                {this.state.errorInfo.componentStack}
              </details>
            </div>
          );
        }
        return this.props.children;
      }
    }

    const ErroneousComponent = () => {
      throw new Error('Simulated error');
      return (<div>If you see this, no error was thrown.</div>);  // This line won't be reached
    };

    ReactDOM.render(
      <ErrorBoundary>
        <ErroneousComponent />
      </ErrorBoundary>,
      document.getElementById('app')
    );
  </script>

</body>
</html>
This code sets up a simple React application with an error boundary component. The ErrorBoundary component catches errors in child components and renders a fallback UI instead of the component tree that threw an error, displaying the error message and stack trace. componentDidCatch is used to log the error details which could be sent to an external error tracking service. The CSS styles define a basic visual representation for the error message. The test component, ErroneousComponent, simulates an error that is caught by the error boundary.