Learn Remix · 6/13

Error Handling: Keeping the App Alive

8 min read

Error Handling: Keeping the App Alive aplikacji

Imagine you're building a complex machine, like a friendly robot that makes breakfast. 🤖 One morning, it tries to grab the milk, but the carton is empty. What should it do? Freeze entirely? Throw toast across the room in a fit of rage? Or should it calmly say, "We're out of milk. Would you like juice instead?"

In web development, our apps are those breakfast bots. Things can and will go wrong. A user might try to access a page that doesn't exist, an external API might be down, or there could be a bug in our rendering logic. Without a plan, our entire application could crash, leaving the user with a dreaded blank white screen. That's where error handling comes in. It's the art of anticipating these problems and giving our app a script to follow, ensuring it remains functional and user-friendly, even when things go sideways.

Remix has a robust and elegant approach to error handling that's a real game-changer. It automatically catches most errors, whether they happen on the server or in the browser, and gives you the tools to handle them with grace.


1. The ErrorBoundary Component: Catching Unexpected Rendering Errors 💥

The Problem: You've written a component, but a sneaky bug causes it to crash during rendering. Maybe it's trying to access a property on an undefined object. Without an error boundary, this single faulty component could bring down the entire page.

The Solution: Remix uses a concept you might be familiar with from React: Error Boundaries. However, Remix supercharges them. Any route can export an ErrorBoundary component. If an error occurs while rendering that route's component, or even in its loader or action functions, Remix will render the ErrorBoundary instead.

Think of it as a safety net. If the trapeze artist (your component) slips, the ErrorBoundary catches them, preventing a catastrophic fall for the whole circus (your app).

Let's see it in action:

Imagine a route at app/routes/my-buggy-route.tsx that has a component that will inevitably crash.

tsx
// app/routes/my-buggy-route.tsx
export default function MyBuggyRoute() {
  throw new Error("I've fallen and I can't get up!");
  return <div>This will never be seen.</div>;
}

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

  if (isRouteErrorResponse(error)) {
    return (
      <div>
        <h1>
          {error.status} {error.statusText}
        </h1>
        <p>{error.data}</p>
      </div>
    );
  } else if (error instanceof Error) {
    return (
      <div>
        <h1>Error</h1>
        <p>{error.message}</p>
        <p>The stack trace is:</p>
        <pre>{error.stack}</pre>
      </div>
    );
  } else {
    return <h1>Unknown Error</h1>;
  }
}

In this example, when MyBuggyRoute attempts to render, it will throw an error. Remix will catch this and render our custom ErrorBoundary component. Inside the ErrorBoundary, we use the useRouteError hook to get information about the error and display it to the user. The isRouteErrorResponse utility helps us differentiate between thrown Response objects (which we'll cover next) and standard Error objects.

Root Error Boundary:

For a general, app-wide safety net, you should define an ErrorBoundary in your app/root.tsx file. This will catch any errors that aren't caught by a more specific, nested error boundary. It's a good practice to still render the Links, Meta, and Scripts components in your root error boundary to ensure the page can still function.

tsx
// app/root.tsx
import {
  Links,
  LiveReload,
  Meta,
  Outlet,
  Scripts,
  ScrollRestoration,
  isRouteErrorResponse,
  useRouteError,
} from "@remix-run/react";

export function ErrorBoundary() {
  const error = useRouteError();
  console.error(error);
  return (
    <html>
      <head>
        <title>Oh no!</title>
        <Meta />
        <Links />
      </head>
      <body>
        <h1>Oops! Something went wrong.</h1>
        <Scripts />
      </body>
    </html>
  );
}

2. Throwing Responses: Handling Expected Errors (404s, 401s) 🧐

The Problem: Not all errors are unexpected bugs. Sometimes, an error is an expected outcome. For instance, a user might navigate to a product page for an item that doesn't exist (a 404 Not Found error), or they might try to access a protected page without being logged in (a 401 Unauthorized error). These aren't application crashes; they are predictable scenarios we need to handle.

The Solution: In Remix, the standard way to handle these expected errors is to throw a Response object from your loader or action functions. This immediately stops the execution of your server-side code and triggers the ErrorBoundary path, but in a more controlled way than a full-blown error.

Imagine a restaurant. If a customer orders a dish that's not on the menu, the waiter doesn't shut down the whole restaurant. They simply inform the customer, "Sorry, we don't have that," and suggest other options. Throwing a Response is your app's way of doing just that.

Example: Handling a 404 Not Found:

Let's say you have a route to display a blog post by its slug: app/routes/posts.$slug.tsx. In your loader, you'll fetch the post from a database. If the post isn't found, you should throw a 404 response.

tsx
// app/routes/posts.$slug.tsx
import { json } from "@remix-run/node";
import { useLoaderData, isRouteErrorResponse, useRouteError } from "@remix-run/react";
import { getPost } from "~/models/post.server";

export const loader = async ({ params }) => {
  const post = await getPost(params.slug);
  if (!post) {
    throw new Response("Not Found", { status: 404 });
  }
  return json({ post });
};

export default function PostRoute() {
  const { post } = useLoaderData<typeof loader>();
  return (
    <main>
      <h1>{post.title}</h1>
      <div dangerouslySetInnerHTML={{ __html: post.html }} />
    </main>
  );
}

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

  if (isRouteErrorResponse(error) && error.status === 404) {
    return <div>Post not found</div>;
  }

  return <div>Something went wrong</div>;
}

Here, if getPost returns null, we throw new Response("Not Found", { status: 404 });. Remix catches this and renders our ErrorBoundary. Inside the boundary, we can check the error.status and display a user-friendly "Post not found" message. A huge benefit is that your main component (PostRoute) doesn't need to worry about the "not found" case; it can assume it will always receive a valid post.


3. Contextual Errors: Displaying Failures Within Nested Routes 🖼️

The Problem: Your application has a complex layout with nested routes. For example, a dashboard with a sidebar and a main content area. If an error occurs in the main content area, you don't want the entire dashboard, including the sidebar, to be replaced by an error message. That would be a jarring user experience.

The Solution: This is where the true power of Remix's error handling shines. Errors are handled in isolation. If a nested route has an ErrorBoundary, only that part of the UI will be replaced when an error occurs. The parent routes and their layouts will remain interactive.

This is like having a fire alarm system with zones. If a small fire starts in the kitchen, only the kitchen's sprinkler system activates. The rest of the house remains unaffected.

Example: An Error in a Nested Dashboard Panel:

Consider this route structure:

  • app/routes/dashboard.tsx (the main layout with a sidebar)
  • app/routes/dashboard.sales.tsx (a panel within the dashboard)
tsx
// app/routes/dashboard.tsx
import { Outlet } from "@remix-run/react";

export default function Dashboard() {
  return (
    <div>
      <nav>/* Sidebar navigation */</nav>
      <main>
        <Outlet />
      </main>
    </div>
  );
}
tsx
// app/routes/dashboard.sales.tsx
export default function SalesPanel() {
  // Let's pretend this component has a rendering error
  throw new Error("Failed to load sales data!");
  return <div>Sales Data</div>;
}

export function ErrorBoundary() {
  return (
    <div className="error-container">
      <h2>Oops! The sales panel failed to load.</h2>
      <button onClick={() => window.location.reload()}>Try again</button>
    </div>
  );
}

When you navigate to /dashboard/sales, the SalesPanel will throw an error. Because dashboard.sales.tsx has its own ErrorBoundary, Remix will render that boundary inside the <Outlet /> of the dashboard.tsx layout. The user will see the error message for the sales panel, but the main dashboard sidebar will still be visible and usable. If a route doesn't have an error boundary, the error "bubbles up" to the nearest one in the hierarchy, all the way to the root if necessary.


4. Graceful Degradation: Designing Helpful Fallback UIs 🎨

The Problem: Simply displaying a raw error message or a stack trace isn't very helpful to the average user. It can be intimidating and doesn't tell them what to do next.

The Solution: Graceful degradation is about designing your error UIs (your ErrorBoundary components) to be as helpful as possible. Instead of just showing what went wrong, guide the user on what to do next. A good fallback UI can turn a frustrating experience into a manageable one.

Think of it as the friendly flight attendant during turbulence. They don't just announce, "The plane is shaking!" They calmly say, "We're experiencing some turbulence. Please return to your seats and fasten your seatbelts. We expect it to pass shortly."

Best Practices for Fallback UIs:

  • Keep it Simple and Clear: Avoid technical jargon. Use plain language to explain that something went wrong.
  • Provide a Way Out: Always include a link back to the homepage or a "try again" button. This gives the user control and prevents them from feeling stuck.
  • Maintain Branding: Your error page should still look like your app. Use your standard layout, header, and footer. This reassures the user that they are still on your site.
  • Use Skeleton Loaders for Pending States: While not strictly error handling, providing skeleton UIs while data is loading can improve the user's perception of performance and act as a graceful transition before content (or an error) appears.

Here is a more user-friendly ErrorBoundary:

tsx
export function ErrorBoundary() {
  const error = useRouteError();

  // It's a good idea to log the error for debugging
  console.error(error);

  return (
    <div className="error-page">
      <h1>Something Went Wrong</h1>
      <p>We're sorry, but an unexpected error occurred.</p>
      <a href="/">Go back to the homepage</a>
    </div>
  );
}

By thoughtfully implementing these error handling patterns, you can build Remix applications that are not only powerful and fast but also remarkably resilient and user-friendly.

Extra Reading & References 📚

Challenge

Challenge: Implement a Resilient Product Page Error Boundary

Your task is to build a robust ErrorBoundary for a product details page in a Remix application. This boundary needs to gracefully handle two distinct types of errors that can be thrown from its loader function: an expected 'Not Found' error and an unexpected server error.

Requirements:

  1. Export a component named ErrorBoundary from the route module.
  2. Inside the ErrorBoundary, use the useRouteError hook to capture the thrown error.
  3. Implement logic using isRouteErrorResponse to determine the type of error.
  4. If the error is a Response object (e.g., a 404 Not Found):
    • Render an <h1> that says "Product Not Found".
    • Render a <p> that includes the error's status and status text, for example: "Status: 404 - Not Found".
  5. If the error is a standard JavaScript Error:
    • Log the error to the console for debugging purposes using console.error(error).
    • Render an <h1> with the text "Something went wrong".
    • Render a <p> containing the specific message from the error object.
  6. For both error scenarios, the component should also render an anchor tag (<a>) that links the user back to the homepage (href="/") with the text "Go to Homepage".

Expected result

Your code should export a function component named ErrorBoundary.

This component must perform the following actions:

  • It calls the useRouteError() hook to get the error object.
  • It uses an if/else or ternary statement with isRouteErrorResponse(error) to check the error type.
  • If the error is a Response, it must render an <h1> and <p> displaying the custom "Product Not Found" message and the error's status/status text.
  • If the error is a standard Error instance, it must call console.error with the error, and then render an <h1> and <p> displaying a generic message and the specific error.message.
  • In all cases, a final <a> tag with href="/" must be rendered to allow the user to navigate away.
typescript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.