Accept: text/markdown header. For an index of Next.js Pages Router documentation, see /docs/pages/llms.txt.catchError
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.
import { catchError, type ErrorInfo } from 'next/error'
function ErrorFallback(props: { title: string }, { error, reset }: ErrorInfo) {
return (
<div>
<h2>{props.title}</h2>
<p>{error.message}</p>
<button onClick={() => reset()}>Try again</button>
</div>
)
}
export default catchError(ErrorFallback)Reference
Parameters
catchError accepts a single argument:
const ErrorWrapper = catchError(fallback)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:
import ErrorWrapper from './custom-error-boundary'
export default function Component({ children }: { children: React.ReactNode }) {
return <ErrorWrapper title="Dashboard Error">{children}</ErrorWrapper>
}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.
import { catchError, type ErrorInfo } from 'next/error'
function ErrorFallback(props: {}, { error, reset }: ErrorInfo) {
return (
<div>
<p>{error.message}</p>
<button onClick={() => reset()}>Try again</button>
</div>
)
}
export default catchError(ErrorFallback)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. |
Was this helpful?