Sub topic 13
Handling errors per route
This chapter covers how React Router (the data router API) catches errors at the route level and decides what to show. It assumes you know the following:
- You can define routes with
createBrowserRouterand nest them withOutlet. - You know what a loader is and how
useLoaderDatareturns its result. - You are comfortable with
async/await,fetch, and JSX.
Why errors belong to routes
Without error handling, one failed fetch in a loader or one exception during rendering can blank the whole page. React Router lets each route declare what to show when something inside it fails. The failing route shows an error screen, and the rest of the page keeps working.
A route's errorElement is rendered in place of the route's element when any of these happens:
- A loader throws or rejects.
- An action throws or rejects.
- The route's component (or a child component) throws while rendering.
- No route matches the URL. The router creates a 404 error for this case.
If the route has no errorElement, the error bubbles up to the nearest ancestor that has one. If no route has one, React Router shows its built-in default screen. That screen is meant for development, so you should always supply your own at the top.
A loader, an error element, and the thrown Response
This is the core pattern. The loader throws a Response when the server reports a problem. The error element reads the error with useRouteError.
import {
createBrowserRouter,
useLoaderData,
useRouteError,
isRouteErrorResponse,
} from "react-router-dom";
async function userLoader({ params }) {
const res = await fetch(`/api/users/${params.userId}`);
if (!res.ok) {
throw new Response("User not found", { status: res.status });
}
return res.json();
}
function User() {
const user = useLoaderData();
return <h1>{user.name}</h1>;
}
function UserError() {
const error = useRouteError();
if (isRouteErrorResponse(error)) {
return <p>{error.status}: {error.data}</p>;
}
return <p>Something went wrong.</p>;
}
const router = createBrowserRouter([
{
path: "/users/:userId",
element: <User />,
loader: userLoader,
errorElement: <UserError />,
},
]);Two points matter here.
fetchonly rejects on network failure. A 404 or 500 response resolves normally, so you must checkres.okyourself and throw. If you skip the check,res.json()may succeed on an error body, andUserrenders with bad data.- The loader throws instead of returning. A returned value always counts as success and goes to
useLoaderData. A thrown value always goes to the error element.
Two kinds of errors: responses and everything else
useRouteError returns whatever was thrown. You need to tell two shapes apart.
| Thrown value | Typical source | How to detect | Useful fields |
|---|---|---|---|
| `Response` (wrapped by the router) | `throw new Response(...)`, or an unmatched URL | `isRouteErrorResponse(error)` is `true` | `status`, `statusText`, `data` |
| `Error` or other value | A bug in a component, a network `TypeError`, a failed `JSON.parse` | `isRouteErrorResponse(error)` is `false` | `message`, `stack` |
error.data holds the body you passed to new Response. For an unmatched URL, the router produces a 404 error response, so the same isRouteErrorResponse branch handles it.
A reusable error element that handles both shapes:
import { useRouteError, isRouteErrorResponse, Link } from "react-router-dom";
export function RouteError() {
const error = useRouteError();
if (isRouteErrorResponse(error)) {
const title = error.status === 404 ? "Page not found" : `Error ${error.status}`;
return (
<section>
<h1>{title}</h1>
<p>{typeof error.data === "string" ? error.data : error.statusText}</p>
<Link to="/">Back to home</Link>
</section>
);
}
const message = error instanceof Error ? error.message : "Unknown error";
return (
<section>
<h1>Unexpected error</h1>
<p>{message}</p>
</section>
);
}Bubbling and where to place the boundary
Where you put errorElement decides how much of the page is replaced. React Router starts at the route where the error happened and walks up the route tree. It renders the first errorElement it finds in that route's place. Everything above that route keeps rendering.
If you put errorElement on the layout route itself, the error element replaces the layout, including its navigation bar. Users lose the nav and may feel stuck. To keep the layout visible, add a pathless child route that carries the error element and wraps the real pages:
import { createBrowserRouter, Outlet, Link } from "react-router-dom";
import { RouteError } from "./RouteError";
function Layout() {
return (
<div>
<nav>
<Link to="/">Home</Link> <Link to="/users/1">User 1</Link>
</nav>
<Outlet />
</div>
);
}
const router = createBrowserRouter([
{
path: "/",
element: <Layout />,
errorElement: <RouteError />, // last resort, replaces the whole layout
children: [
{
errorElement: <RouteError />, // pathless: catches child errors, layout stays
children: [
{ index>Home</h1> },
{
path: "users/:userId",
element: <h1>User</h1>,
loader: async ({ params }) => {
const res = await fetch(`/api/users/${params.userId}`);
if (!res.ok) throw new Response("User not found", { status: res.status });
return res.json();
},
},
],
},
],
},
]);A pathless route has no path, so it adds no URL segment. It only adds a place for the error boundary. The outer errorElement still catches failures in Layout itself.
404 pages: unmatched URLs and splat routes
When no route matches, the router raises a 404 error. You have two ways to show a custom 404 page.
- Let the error bubble to an
errorElementand branch onerror.status === 404, asRouteErrordoes above. The URL does not match any route, so the error is attributed to the root. - Add a catch-all (splat) route as the last child,
{ path: "*", element: <NotFound /> }. This route does match, so it renders as a normal page inside the layout, and the nav stays visible.
Option 2 is simpler when you want a 404 inside the layout. Option 1 gives one place to handle every status code. You can combine them. Use a splat route for unknown URLs, and throw a 404 Response from loaders when a record is missing, as in userLoader.
Errors from actions and rendering
Actions follow the same rules as loaders. If an action throws, the nearest errorElement renders. If you want to show a validation problem next to the form instead, return the error data and read it with useActionData. Reserve throw for failures the user cannot fix by editing the form, such as a server outage.
Render-time exceptions also reach errorElement. This catches a component that reads a property of undefined, for example. It does not catch errors in event handlers or in setTimeout callbacks. Those are outside React's rendering and must be handled with try/catch.
Common mistakes
- Calling
useRouteErroroutside an error element. It returns the route error only inside a route's error boundary. - Forgetting
res.okin a loader, so server errors look like success. - Putting the only
errorElementon the layout route, so every error removes the navigation. - Treating every thrown value as a
Response. Always check withisRouteErrorResponsebefore readingstatus. - Returning
new Response(...)instead of throwing it. Returned values are success data.
Exercise
A layout route at "/" has an errorElement and renders a nav bar plus an Outlet. A child route "reports" has no errorElement, and its loader throws new Response("Forbidden", { status: 403 }). What does the user see, and how would you keep the nav bar on screen?
Show answer
The error bubbles to the layout's errorElement, which replaces the layout, so the nav bar disappears and the 403 is shown in its place. To keep the nav, give "reports" its own errorElement, or wrap the child routes in a pathless route that has the errorElement, so the error element renders inside the layout's Outlet.
Exercise
In a loader you call fetch("/api/orders/7") and the server responds with status 500. The loader does not check res.ok and returns res.json(). Which will happen: the errorElement renders, or the route renders with data? How do you fix it?
Show answer
The route renders with whatever res.json() returns, because fetch resolves on a 500 response and nothing was thrown. Fix it by checking if (!res.ok) throw new Response("Could not load order", { status: res.status }); before parsing the body.