Error Handling and Boundaries
Relevant source files
The following files were used as context for generating this wiki page:
- packages/react-reconciler/src/ReactFiberThrow.js
- packages/react-reconciler/src/ReactFiberUnwindWork.js
- packages/react-reconciler/src/ReactFiberErrorLogger.js
- packages/react-reconciler/src/tests/ReactErrorBoundaries-test.internal.js
- packages/react-reconciler/src/tests/ReactIncrementalErrorHandling-test.internal.js
- packages/react-devtools-shared/src/tests/inspectedElement-test.js
- packages/react-devtools-shared/src/tests/store-test.js
React's error handling mechanism is primarily built around the concept of "Error Boundaries". These are special components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the component tree that crashed. This prevents a UI-breaking error in one part of the application from corrupting the entire application state and display.
The system is designed to be robust, handling errors that occur during rendering, in lifecycle methods, and in constructors of the whole tree below them. The reconciler manages a sophisticated process of unwinding the component stack to find the nearest boundary, allowing it to recover gracefully and maintain a consistent UI. This process is tightly integrated with development tools to provide detailed logging and debugging capabilities.
Error Boundaries
An Error Boundary is a class component that defines one or both of the static lifecycle method getDerivedStateFromError() or the instance method componentDidCatch().
static getDerivedStateFromError(error): This method is called during the "render" phase after a descendant component has thrown an error. It should return a value to update state, which causes the boundary to re-render with a fallback UI.componentDidCatch(error, errorInfo): This method is called during the "commit" phase. It is used for side effects like logging the error to an external service. It receives theerroritself and anerrorInfoobject with acomponentStackproperty.
Sources: packages/react-reconciler/src/tests/ReactErrorBoundaries-test.internal.js:338-366
Class Diagram
This diagram shows the structure of a typical Error Boundary component.
Key Lifecycle Methods
| Method | Phase | Purpose |
|---|---|---|
getDerivedStateFromError() | Render | Renders a fallback UI when an error is thrown in a descendant. |
componentDidCatch() | Commit | Logs error information for debugging and reporting. |
Sources: packages/react-reconciler/src/tests/ReactErrorBoundaries-test.internal.js:1252-1271, packages/react-reconciler/src/tests/ReactIncrementalErrorHandling-test.internal.js:63-76
Error Propagation and Unwinding
When an error is thrown within a component, React initiates a two-phase process to handle it. This ensures that the application can recover gracefully without entering a broken state.
1. The Throw Phase
When an error occurs in a component's render method or lifecycle, React's reconciler captures the exception. The internal throwException function is responsible for this. It captures the value thrown and the source fiber, creating a "captured value" object that includes the error and the component stack.
Sources: packages/react-reconciler/src/ReactFiberThrow.js
2. The Unwind Phase
After an error is captured, the "unwind" phase begins. The reconciler walks up the fiber tree from the component that threw the error, looking for the nearest parent with an error boundary.
The unwindWork function in the reconciler is central to this process. It checks each parent fiber to see if it is an error boundary (i.e., if it has getDerivedStateFromError or componentDidCatch).
- If an error boundary is found, the reconciler updates its state using
getDerivedStateFromErrorand schedules an update to render the fallback UI. The unwinding process stops here. - If no boundary is found, the process continues up the tree until it reaches the root. If the root is reached without finding a boundary, the entire React component tree is unmounted, and the error is re-thrown.
Sources: packages/react-reconciler/src/ReactFiberUnwindWork.js
This flowchart illustrates the error handling and unwinding process.
Error Logging
React provides mechanisms for logging both caught (by an Error Boundary) and uncaught errors. This is primarily handled by the ReactFiberErrorLogger.js module.
Caught vs. Uncaught Errors
- Caught Errors: Errors caught by an error boundary are passed to
logCaughtError. The default implementation (defaultOnCaughtError) logs a detailed message to the console, including the component stack and the name of the error boundary that caught the error. This helps developers understand where the error occurred and how it was handled. - Uncaught Errors: If an error is not caught by any boundary, it propagates to the root and is passed to
logUncaughtError. The default implementation (defaultOnUncaughtError) reports the error as a global, uncaught exception and logs a warning suggesting the addition of an error boundary.
These logging functions can be overridden at the root level for custom error reporting, for example, sending reports to an external monitoring service.
Sources: packages/react-reconciler/src/ReactFiberErrorLogger.js:28-112
Logging Sequence
The following diagram shows the sequence of events when an error is caught and logged.
Asynchronous Rendering and Retries
In asynchronous rendering mode, React has a more sophisticated recovery mechanism. If an error is thrown during an async render, React doesn't immediately commit the fallback UI. Instead, it completes the current render pass up to the boundary and then attempts to re-render the tree synchronously one more time.
This "retry" mechanism is designed to handle data races where the error might be transient and resolved by the time the render completes. If the retry also fails, React then proceeds to commit the error boundary's fallback UI.
If a new, lower-priority update is scheduled while an error is pending, React will attempt to recover by rendering all pending updates in a single, synchronous batch. If this succeeds, the error is discarded, and the UI is updated to the new state.
Sources: packages/react-reconciler/src/tests/ReactIncrementalErrorHandling-test.internal.js:101-140, 172-192
DevTools Integration
React DevTools provides enhanced visibility and control over error handling.
Error and Warning Badges
The component tree in DevTools displays badges next to components that have logged errors or warnings during their render or lifecycle methods. The store keeps track of componentWithErrorCount and componentWithWarningCount.
Sources: packages/react-devtools-shared/src/tests/store-test.js:1140-1156
Inspecting and Toggling Errors
When an error boundary is inspected in DevTools, it provides information about its error state. For components inside an error boundary, DevTools can show whether the component is currently in an errored state (isErrored).
Furthermore, DevTools allows developers to manually toggle the error state of a boundary. This is exposed via the canToggleError property on the inspected element data. This feature is useful for testing fallback UIs without having to manually trigger an error in the application code.
Sources: packages/react-devtools-shared/src/tests/inspectedElement-test.js:1700-1773
Summary
React's error handling is a core feature of its reconciler, designed to ensure application stability and provide a great developer experience. By using Error Boundaries, developers can gracefully handle runtime errors in their component tree. The internal unwind-and-catch mechanism, combined with a robust retry strategy for asynchronous rendering and detailed logging, allows applications to remain responsive and debuggable even when unexpected errors occur. Integration with DevTools further empowers developers to inspect, debug, and test error states effectively.