Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 50 ยท Data Mode

Error Boundaries and Error Elements

Handle loader, action and render errors with errorElement, read them with useRouteError and isRouteErrorResponse, nest boundaries, and send 404s from loaders.

Things go wrong in routed apps in ways that plain components rarely see. A loader's request fails, an action is rejected with 403, the product behind /products/99 does not exist, a typo in a URL matches nothing, or a component throws while rendering. Without a plan, any of these ends in a blank screen or the router's bare development error page.

React Router gives every route a place to say what should happen instead: an error element. When something fails in a loader, an action or the route's own rendering, the router renders the nearest error element instead of the route's normal content, and the rest of the page keeps working. In this lesson you will attach error elements to routes, read the error with useRouteError, tell HTTP-style errors from unexpected ones with isRouteErrorResponse, nest boundaries so failures stay small, and throw 404s from loaders. It builds on loaders and on React's own error boundaries, which route error elements are based on.

errorElement and useRouteError

Error elements live on route objects of a data router. Each route can have an errorElement (an element) or an ErrorBoundary (a component, the same thing in component form). Inside it, useRouteError() returns whatever was thrown:

JSX
// router.jsx - React Router (read-only)
import { createBrowserRouter } from 'react-router';

const router = createBrowserRouter([
  {
    path: '/',
    element: <Root />,
    errorElement: <RootError />,
    children: [
      { index: true, element: <Home /> },
      {
        path: 'projects/:id',
        element: <Project />,
        loader: projectLoader,
      },
    ],
  },
]);
JSX
// root-error.jsx - React Router (read-only)
import { isRouteErrorResponse, Link, useRouteError } from 'react-router';

export function RootError() {
  const error = useRouteError();

  if (isRouteErrorResponse(error)) {
    return (
      <main>
        <h1>
          {error.status} {error.statusText}
        </h1>
        <p>{typeof error.data === 'string' ? error.data : 'The request failed.'}</p>
        <Link to="/">Back to the home page</Link>
      </main>
    );
  }

  return (
    <main>
      <h1>Something went wrong</h1>
      <p>We have been notified. Try again in a moment.</p>
      <Link to="/">Back to the home page</Link>
    </main>
  );
}

isRouteErrorResponse(error) is the question every error element should ask first. It is true when the error is a response-style error that your code threw on purpose, such as throw data('Not found', { status: 404 }) (or throw new Response(...)), and then error.status, error.statusText and error.data are available. When it is false, you have an ordinary exception: a TypeError from your own bug, or an Error thrown by a failing fetch wrapper. For those, do not show the message to visitors in production; log it and display something generic.

Real library or stand-in? The react-router code is the real v7 API. The live examples use a small hand-written router on React and location.hash. It has a nested route tree, loaders that can throw, errorElement on routes, and a useRouteError hook, plus tiny stand-ins for data() and isRouteErrorResponse. Its loaders run synchronously during render to keep the demo short, whereas real loaders are usually async and run before rendering. Declarative mode (<BrowserRouter> with <Routes>) has no errorElement at all: it is a data-router feature.

What counts as an error

A route's error element is shown when any of these happen for that route:

  • Its loader or action throws or rejects (including a thrown data(...) or Response).
  • A component in the route throws while rendering (this is the familiar React error boundary behavior).
  • A fetcher load or submission for a route throws.
  • No route matches the URL at all. A data router reports this as a 404 response error and renders the root route's error element.

What is not caught: errors inside event handlers (onClick) and inside setTimeout callbacks or effects. Those never reach React's error handling, so handle them with try/catch and show the failure yourself, the same rule as plain React.

You should always give the root route an error element. Without one, the router shows a built-in, developer-oriented error page.

Nested boundaries: errors bubble up

An error element catches errors from its own route and every descendant that has no error element of its own. The router looks for the nearest boundary on the way up the route tree, starting at the route that failed:

flowchart TD
    A["Root route<br/>errorElement"] --> B["Projects layout<br/>errorElement"]
    B --> C["projects/:id<br/>loader throws 404"]
    C -. "no errorElement here,<br/>so bubble up" .-> B
    A --> D["admin<br/>loader throws 403"]
    D -. "no errorElement here<br/>or in between" .-> A

The 404 from projects/:id is caught by the Projects layout's boundary. The 403 from admin has nothing nearer, so the root boundary shows it.

Two things follow from this:

  1. The boundary replaces the route that owns it. The error element renders in the slot where that route would have rendered. Everything above it (headers, sidebars of ancestor layouts) stays on screen. Everything below it is gone.
  2. Closer boundaries keep more of the page. An error element on a leaf route keeps the parent layout, including its heading and navigation, so a failed detail view does not take the list down with it.

Choose the level on purpose: a boundary on every route is noisy to maintain, a single root boundary turns every small failure into a full-page error. A good default is the root route, plus one on any layout whose children load unreliable data.

The first example shows all of this. It has a root boundary, a boundary on the Projects layout and an optional boundary on the :id route you can switch on. Try each link.

Nested error boundaries

Walk through it. "Project 99" with the checkbox off is caught by the Projects boundary (orange): the layout heading is gone because the boundary replaced that whole route. Turn the checkbox on and the same link now shows the blue boundary inside the layout heading. "Admin" has no boundary of its own or on its parent chain below the root, so the root boundary (red) replaces the shell, navigation included. "Nowhere" matches no route at all, and the root boundary renders a 404 for that too.

404s from loaders

A route that matches a URL is not the same as a record that exists. The pattern projects/:id matches /projects/99, but there may be no project 99. The loader is the right place to check, because it runs before the component and can stop the render:

JSX
// project-loader.jsx - React Router (read-only)
import { data } from 'react-router';

export async function projectLoader({ params }) {
  const response = await fetch(`/api/projects/${params.id}`);

  if (response.status === 404) {
    throw data(`No project with id ${params.id}`, { status: 404 });
  }
  if (!response.ok) {
    throw new Error('The projects API failed with ' + response.status);
  }
  return response.json();
}

This split is the important design habit: throw data(...) for failures you expect and can describe to the user (not found, forbidden, invalid input), and throw errors or let them fail for the unexpected ones. The component can then assume useLoaderData() is always valid, with no if (!project) branches. On a server-rendered app the same thrown data becomes the HTTP status of the response, which is how real 404s are produced (see 404 Pages and Catch-All Routes).

Actions follow the same rules. A failed validation is usually returned from the action and shown next to the form (see Actions and Form), while something like "you are not allowed to do this" is thrown so the error element takes over.

Writing one error component for the whole app

Most apps use one reusable error component for the root and a few layouts. It decides what to show from the kind of error:

Classifying route errors

The same component works at every level of the tree. Because error.status is just a number, you can add cases for 403 (explain permissions) or 503 (suggest trying later) in one place.

Good error-handling habits

  • Root first. Always give the root route an error element, then add more where a failure should stay small.
  • Offer a way out. Link home, offer "try again" (a link to the same URL re-runs the loaders), and keep the site chrome visible where you can.
  • Do not leak details. Show stack traces and raw messages only in development.
  • Log what you cannot show. Send unexpected errors to your monitoring service from the error component (in an effect) or from a shared helper.
  • Test the unhappy paths. Visit the 404 and the failing-API pages on purpose while developing.
  • Streamed data fails separately. A rejected promise inside Await has its own errorElement (see Streaming Data with Await and Suspense).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A child route's loader throws, and neither that route nor its parent defines an errorElement, but the root route does. What happens?

    Errors bubble up to the nearest ancestor with an error element. The boundary replaces the route that owns it, so here the whole root route's content is replaced.
  2. 2. What does isRouteErrorResponse(error) tell you?

    It separates deliberate response errors, which have an HTTP-like status, from ordinary exceptions such as a TypeError.
  3. 3. You want a failed project detail page to keep the surrounding projects layout (heading and sidebar) on screen. Where should the error element go?

    A boundary replaces the route that owns it and keeps everything above. The closer to the failure it sits, the more of the page survives.
  4. 4. Which failure is NOT caught by a route's error element?

    Event handler errors never reach React's render error handling. Catch them with try/catch and show the failure yourself.
  5. 5. Why should a loader throw data('...', { status: 404 }) for a missing record instead of returning null?

    Throwing stops the route from rendering with missing data, sends the failure to the error element, and on a server becomes the real response status.

Summary

  • Give routes of a data router an errorElement (or ErrorBoundary) and read the failure with useRouteError().
  • Errors from loaders, actions, fetchers, rendering and unmatched URLs reach the nearest boundary up the route tree; event handler errors do not.
  • A boundary replaces the route that owns it and keeps ancestors on screen, so leaf boundaries preserve more of the page.
  • Use isRouteErrorResponse to separate deliberate response errors (status, statusText, data) from unexpected exceptions, and show generic messages for the latter.
  • Throw data(message, { status: 404 }) from loaders when a record does not exist, so components never handle missing data.
  • Always define a root error element; add nested ones where failures should stay local.

Next: Lazy Routes and Code Splitting