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:
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:
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.