Sub topic 13
Handling errors per route
This chapter assumes you can define routes with createBrowserRouter, nest them with Outlet, and write a loader that fetches data. It builds on those pieces.
What counts as an error
Without error handling, an uncaught error in a route shows React Router's default error screen. A route can fail in four ways:
- A loader or action throws.
- A component throws while rendering.
- No route matches the URL.
- A loader or action throws a
Response, such as a 404 from a failedfetch.
Each route can have an errorElement. When something fails, the router renders that element in place of the route's element.
Bubbling to the nearest errorElement
If a route has no errorElement, the error bubbles up to the closest parent that has one. Put one on the root route as a safety net. Add more on child routes so a failure replaces only that part of the page.
Where the error is handled decides how much of the page is replaced. If the child route handles it, the layout, including its navigation, stays on screen.
Reading the error
Inside an errorElement, call useRouteError to get what was thrown. Use isRouteErrorResponse to tell a thrown Response apart from a plain Error.
import {
createBrowserRouter,
RouterProvider,
Outlet,
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 ErrorPage() {
const error = useRouteError();
if (isRouteErrorResponse(error)) {
return <p>{error.status}: {error.data}</p>;
}
return <p>Something went wrong: {error.message}</p>;
}
const router = createBrowserRouter([
{
path: "/",
element: <Outlet />,
errorElement: <ErrorPage />,
children: [
{ path: "users/:userId", element: <User />, loader: userLoader },
],
},
]);
export default function App() {
return <RouterProvider router={router} />;
}Here the root route's ErrorPage handles everything. A failed user fetch shows 404: User not found. A URL that matches no route also produces a 404 response, so the same component covers it.
A catch-all route for 404 pages
You can also match unknown URLs explicitly with a splat route, path: "*". It renders as a normal page inside the layout, so the navigation stays visible.
{ path: "*", element: <h1>Page not found</h1> }Use the catch-all for friendly 404 pages inside a layout. Use errorElement for failures.
Exercise
A user route has a loader that throws, and its parent layout route has an errorElement. The user route has none. What does the user see, and is the layout's navigation still visible?
Show answer
The error bubbles to the layout's errorElement, which renders in place of the whole layout. The layout's navigation is gone, because the layout's own element was replaced. Adding an errorElement to the user route would keep the layout and its navigation on screen.