Handling Errors

Explicit Error Boundary

This example was originally created as one of several examples I wrote for a post about errors and retry for React Server Components. See that post for a more detailed explanation of the concepts here.

This example demonstrates how to use an explicit error boundary to catch errors thrown by a server component. The process is very much the same as with client components, with the only difference being that the error boundary is a server component itself.

This example uses the simple react-error-boundary library to create the error boundary. It's pretty easy to roll your own if you prefer.

Here's the code:

page.tsx
import { ErrorBoundary } from 'react-error-boundary'

export default function PageWithBoundary() {
return (
<>
<p>
This page demonstrates what happens when an error is thrown in a
component with an explicit error boundary.
</p>

<ErrorBoundary fallback={<ErrorFallback />}>
<ErrorComponent />
</ErrorBoundary>
</>
)
}

function ErrorComponent() {
throw new Error('Error thrown in component')

return 'This will never be rendered'
}

function ErrorFallback() {
return (
<div className="text-red-700">There was an error with this content</div>
)
}

That's it! The ErrorBoundary component will catch any errors thrown by its children and render the fallback component instead. This is a much better user experience than the default behavior, which is to render either and error or nothing at all.

Here's how that looks:

This is what you will see when an error is thrown in a component with an error boundary
This is what you will see when an error is thrown in a component with an error boundary

Live Demo

This example can't be easily inlined as it demonstrates how a full-page feels to the end user. Here it is inside an iframe, and there's a looping video below too.

This is an iframe pointing to /examples/errors/error-boundary

Similar Examples

Using error.tsx

pageerrorboundary

Using the error.tsx convention to catch errors

No error handling

pageerror

When happens out of the box when you have an RSC error and don't handle it

Previous
No boundaries