catchError
API Reference for the catchError function.
The catchError function creates a component that wraps its children in an error boundary. It provides a programmatic alternative to writing a custom React error boundary class, enabling component-level error recovery anywhere in your component tree.
Compared to a custom React error boundary, catchError is designed to work with Next.js out of the box:
- Built-in error recovery —
reset()re-renders the error boundary's children, letting users recover from errors without a full page reload. - Client navigation handling — The error state automatically clears when you do a client navigation to a different route.
Reference
Parameters
catchError accepts a single argument:
fallback
A function that renders the error UI when an error is caught. It receives two arguments:
props— The props passed to the wrapper component (excludingchildren).errorInfo— An object containing information about the error:
| Property | Type | Description |
|---|---|---|
error | Error | The error instance that was caught. |
reset | () => void | Resets the error state and re-renders the error boundary's children. |
Returns
catchError returns a React component that:
- Accepts the same props as your fallback's first argument, plus
children. - Wraps
childrenin an error boundary. - Renders the
fallbackwhen an error is caught inchildren.
Examples
Basic usage
Define a fallback and use the returned component to wrap parts of your UI:
Recovering from errors
Use reset() to prompt the user to recover from the error. When called, the function clears the error state and re-renders the error boundary's children.
Good to know: Props passed to the wrapper component are forwarded to the fallback function, making it easy to create reusable error UIs with different configurations.
Version History
| Version | Changes |
|---|---|
v16.3.0 | catchError became stable. |
v16.2.0 | unstable_catchError introduced. |