Sub topic 13
Error boundaries and 404 responses
This chapter assumes you can write a loader (a function that fetches data on the server for a route) and that you know HTTP status codes. It builds on the loader and root route chapters.
Two kinds of errors
A route module can fail in two ways, and React Router handles them differently.
- Thrown responses are errors you throw on purpose, such as a 404 for a missing record. You create them with
data()orthrow new Response(...). - Unexpected errors are everything else: a bug in a component, a failed database call, a
TypeError.
Both are caught by the nearest ErrorBoundary export. Instead of the route's normal component, React Router renders the boundary in that route's place.
Throwing a 404 from a loader
If a loader cannot find the record, throw. Returning null would force every component to check for it.
import { data } from "react-router";
import type { Route } from "./+types/detail";
import { getContact } from "~/contacts.server";
export async function loader({ params }: Route.LoaderArgs) {
const contact = await getContact(params.contactId);
if (!contact) {
throw data("Contact not found", { status: 404 });
}
return { contact };
}
export default function ContactDetail({ loaderData }: Route.ComponentProps) {
return <h1>{loaderData.contact.name}</h1>;
}Because the loader throws, the component only runs when contact exists. The response also carries a real 404 status, so crawlers and caches see it.
A root-level fallback
Export ErrorBoundary from root.tsx to cover every route that has no boundary of its own.
import { isRouteErrorResponse } from "react-router";
import type { Route } from "./+types/root";
export function ErrorBoundary({ error }: Route.ErrorBoundaryProps) {
if (isRouteErrorResponse(error)) {
return (
<main>
<h1>{error.status} {error.statusText}</h1>
<p>{typeof error.data === "string" ? error.data : null}</p>
</main>
);
}
return (
<main>
<h1>Something went wrong</h1>
</main>
);
}isRouteErrorResponse returns true for thrown responses. It narrows the type so you can read status, statusText, and data. Anything else falls through to a generic message. Do not print error.message from unexpected errors in production, because it can leak internal details.
How the nearest boundary is chosen
React Router walks up the route tree from the route that failed. The first ErrorBoundary it finds handles the error. Siblings and parent layouts stay on screen.
Adding an ErrorBoundary to routes/contacts/detail.tsx keeps the contacts layout, such as a sidebar, visible while only the detail pane shows the error. This is usually better than replacing the whole page.
Common mistakes
- Forgetting the root boundary. Without one, React Router shows a bare default error page.
- Returning instead of throwing.
return data(..., { status: 404 })sends the status but still renders your normal component with that data. Throw when the page cannot render. - Using
error.messagefor thrown responses. A thrown response is not anError. Readerror.datainstead. - Unmatched URLs. A URL that matches no route also produces a 404 response. The root boundary renders it, so handle it there.
Exercise
A loader for /contacts/:contactId finds no contact. Which should it do, return data("Not found", { status: 404 }) or throw data("Not found", { status: 404 }), and why?
Show answer
It should throw. Throwing stops the route from rendering its component and sends control to the nearest ErrorBoundary, so the component never has to handle a missing contact. Returning the response would still render the component with the returned data.