Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 39 ยท Error Handling and Boundaries

Throwing Responses and 404 Pages

Use thrown Response objects and the data() helper for 404, 401 and 403 cases, read them with isRouteErrorResponse, and add a catch-all route for unknown URLs.

Some failures are not bugs. A visitor asks for /projects/999 and project 999 does not exist. That is an expected problem with an exact HTTP meaning: 404 Not Found. Remix and React Router framework mode let a loader or action throw a response for these cases. Throwing stops the function immediately, skips the rest of your code and sends control to the nearest error boundary, which can render a tailored page. The HTTP status code of the document is set to match.

This lesson covers the two ways to throw (a plain Response and the data() helper), how to read the result in a boundary, and how to handle URLs that match no route at all.

Throwing a Response

Anything that is not a normal return can be thrown, but a Response is the standard choice because it carries a status code:

TSX
// app/routes/articles.$slug.tsx (read-only)
import { data } from "react-router";
import type { Route } from "./+types/articles.$slug";

export async function loader({ params }: Route.LoaderArgs) {
  const article = await db.article.findBySlug(params.slug);

  if (!article) {
    // Option 1: a real Response
    throw new Response("Article not found", { status: 404, statusText: "Not Found" });
  }

  if (!article.published) {
    // Option 2: the data() helper, carries any serializable body
    throw data({ reason: "draft" }, { status: 403 });
  }

  return article;
}

data(body, init) is a lightweight wrapper: you give it any serializable value (an object, a string, even a date) and an optional status or headers. It avoids building a real Response and is the recommended style in current React Router. In either case the router wraps what you threw into a route error response with status, statusText and data.

Reading the thrown value in a boundary

isRouteErrorResponse(error) is a type guard: it returns true for thrown responses and data() values and false for ordinary Error objects.

TSX
export function ErrorBoundary({ error }: Route.ErrorBoundaryProps) {
  if (isRouteErrorResponse(error)) {
    if (error.status === 404) {
      return <h1>We could not find that article.</h1>;
    }
    if (error.status === 403) {
      return <h1>This article is still a draft.</h1>;
    }
    return <h1>{error.status} {error.statusText}</h1>;
  }
  return <h1>Unexpected error</h1>;
}

Switching on error.status gives each case its own wording. The common statuses for loaders and actions are:

Status Meaning Typical use
400 Bad request malformed input you cannot continue with
401 Unauthorized not signed in (usually you redirect instead)
403 Forbidden signed in, but not allowed
404 Not found missing record
409 Conflict edit collides with another change
429 Too many requests rate limiting
Node.js Stand-in: throw, catch, classify

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Unknown URLs: the splat route

A URL that matches no route is not an error thrown by your code. The router itself produces a 404 route error. Handle it with a splat route, a route whose path is *. In file-based routing that is app/routes/$.tsx; with a route config it is route("*", "routes/not-found.tsx"):

TSX
// app/routes/not-found.tsx (read-only)
export function loader() {
  throw new Response("Not Found", { status: 404 });
}

export default function NotFound() {
  return null; // never renders; the loader always throws
}

export function ErrorBoundary() {
  return (
    <main>
      <h1>Page not found</h1>
      <a href="/">Back to the home page</a>
    </main>
  );
}

Throwing from the splat's loader is important. Without it the route renders as a normal page and the server answers with status 200, which search engines treat as a real page (a "soft 404"). Always make real 404 pages return a real 404 status.

Throw or return?

Situation Do this
Record not found, forbidden, rate limited throw a response, handled by the boundary
Form input is invalid return errors from the action, shown next to the fields
User must log in first throw redirect("/login") (see protecting routes)
Bug in your code let the exception happen; see unexpected errors

The rule of thumb: if the user can fix it by retyping, return it. If the page cannot be shown at all, throw it.

Node.js Stand-in: soft 404 versus real 404

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is isRouteErrorResponse used for?

    It is a type guard that returns true for route error responses, giving you status, statusText and data.
  2. 2. Why should a catch-all route's loader throw a 404 Response?

    Without the throw the unknown URL renders as a normal page with 200, which search engines may index.
  3. 3. A signup form field is empty. What is the best approach?

    Validation problems are expected and fixable. Returning errors keeps the user on the form with their input.
  4. 4. Which status fits 'you are signed in but not allowed to see this'?

    403 Forbidden means the server understood who you are but refuses access. 401 means not authenticated.

Summary

  • Throw a Response or data(body, { status }) for expected failures such as missing records.
  • isRouteErrorResponse(error) plus error.status lets a boundary tailor its message.
  • A splat route (*) handles unknown URLs; make its loader throw so the status is 404.
  • Return validation errors; throw when the page cannot be shown.

Next: Unexpected Errors and Logging