How to handle errors gracefully in Remix
How to use ErrorBoundary and CatchBoundary in error handling
Thursday, December 16, 2021
How Remix handles errors
From the Remix official documentation
Remix will automatically catch errors and render the nearest error boundary for errors thrown while:
- rendering in the browser
- rendering on the server
- in a loader during the initial server rendered document request
- in an action during the initial server rendered document request
- in a loader during a client-side transition in the browser (Remix serializes the error and sends it over the network to the browser)
- in an action during a client-side transition in the browser
What can we use to handle errors in Remix?
This blog will only discuss how to catch errors using
From the official Docs
An ErrorBoundary is a React component that renders whenever there is an error anywhere on the route, either during rendering or during data loading.
Here is an example of using the
ErrorBoundary component to catch errors in Remix.
ErrorBoundary above, Here are some examples of errors we can catch and the corresponding result.
Explicitly thrown errors
Other errors in backend
Errors in React land
A CatchBoundary is a React component that renders whenever an action or loader throws a Response.
It works in combination with
useCatch. The hook will allow us to get a reference to the response's
will yield to
We can also use other data formats such as plain string,
but we need to make sure our
CatchBoundary can handle them properly.
will yield to
In which cases should we use one over the other?
We should use
CatchBoundary if we care about the context of the error, such as status codes or the custom data related to the error; in another case, we use
The good thing is we can even use them together. So, for example, if there's an error in the
CatchBoundary, that error will be caught by the
Handling global 404 error
Handling route 404 error
Handling error in an action
Try to fill in the form, then click submit to see the
Handing error in a nested route
Propagating error from
/test to the root route
ErrorBoundaryshould not throw an error in a production environment since there's nothing else to catch the error. If the root
ErrorBoundarycan throw an error, the user might see something like this
I find using
CatchBoundary an easy way to handle route errors in Remix as it allows us to have fine-grained control on how we want to display errors in our pages.
In my opinion, it improves the readability of what we are trying to achieve as there is the precise placement of the success and error cases.