Reader small image

You're reading from  Full Stack Web Development with Remix

Product typeBook
Published inNov 2023
Reading LevelIntermediate
PublisherPackt
ISBN-139781801075299
Edition1st Edition
Languages
Tools
Right arrow
Author (1)
Andre Landgraf
Andre Landgraf
author image
Andre Landgraf

Andre is a full stack developer from Germany. He graduated with an MS in Information Systems from the Technical University of Munich and was also awarded an MS in Computer Science from Sofia University in Palo Alto. Andre currently lives in Cupertino, California, and he works as a Software Engineer at LinkedIn. Andre loves learning, writing, and speaking about all things web. In his free time, he tutors aspiring developers and builds for the web.
Read more about Andre Landgraf

Right arrow

Error Handling in Remix

Error handling is an important part of building resilient user experiences. We can distinguish two kinds of errors:

  • Unexpected errors, such as network timeouts
  • Expected failures (exceptions) thrown on purpose

Remix provides primitives and conventions to handle both unexpected and expected errors uniformly. This chapter covers the following topics:

  • Dealing with unexpected errors
  • Handling thrown responses
  • Handling page-not-found (404) errors

First, we will fabricate some unexpected errors and learn how to handle them. Next, we will review the difference between returning and throwing Response objects in loader and action functions. We will see how we can handle thrown responses with Remix’s ErrorBoundary. Finally, we will add not-found error handling to BeeRich.

After reading this chapter, you will understand how to manage both unexpected and expected failures in Remix declaratively using Remix’s ErrorBoundary...

Technical requirements

You can go ahead and use the solution from the previous chapter. No additional setup steps are required for this chapter. If you get stuck, you can find the solution code for this chapter here: https://github.com/PacktPublishing/Full-Stack-Web-Development-with-Remix/tree/main/07-error-handling-in-remix.

Dealing with unexpected errors

During runtime, a Remix application is executed both in the browser and on the server. A lot can go wrong, and unexpected errors can happen both on the client and server. It is important to consider the error case to provide a resilient user experience. In this section, we will investigate how to handle unexpected errors in Remix both at the root level and in nested routes.

Invoking client and server errors

In Chapter 2, Creating a New Remix App, we provided a troubleshooting guide and investigated how Remix handles errors on both the client and server uniformly. Let’s review Remix’s default error handling again by invoking some “unexpected” errors:

  1. Open your BeeRich application in an editor.
  2. Open the dashboard.tsx route module inside the app/routes folder.
  3. Add the following code inside the loader function body before the return statement:
    throw Error('Something went wrong!');

    By throwing an error...

Handling thrown responses

We already take advantage of throwing Response objects in BeeRich. For instance, in Chapter 4, Routing in Remix, we added the following loader function to the dashboard.expenses.$id.tsx route module:

export function loader({ params }: LoaderFunctionArgs) {  const { id } = params;
  const expense = data.find((expense) => expense.id === Number(id));
  if (!expense) throw new Response('Not found', { status: 404 });
  return json(expense);
}

In the loader function, we throw a Response object if we cannot find the expense for the id route parameter. This creates an expected failure during loader function execution. Let’s investigate Remix’s default behavior when an expected exception occurs.

Throwing responses

In JavaScript, the throw statement is used to throw user-defined exceptions. A catch block can then catch the thrown exception. We can throw any value, including Response objects...

Handling page-not-found (404) errors

We can also handle thrown responses in the root ErrorBoundary component. One special case that can only be handled in the root ErrorBoundary component is the page-not-found exception thrown by Remix. Let’s revisit the root error boundary to handle thrown responses at the root level:

  1. Run BeeRich on localhost by executing npm run dev.
  2. Visit a non-existing page such as http://localhost:3000/cheesecake in a new browser window.

    When visiting a non-existing route, Remix throws a response with HTTP status code 404 at the root level. We can use isRouteErrorResponse to render a 404 page using the root error boundary.

  3. Open the root.tsx file in an editor.
  4. Import isRouteErrorResponse from Remix:
    import {  isRouteErrorResponse,  Links,  LiveReload,  Meta,  Outlet,  Scripts,  ScrollRestoration,  useRouteError,} from '@remix-run/react';
  5. Update...

Summary

In this chapter, you learned that Remix lets us handle both expected and unexpected failures declaratively using Remix’s ErrorBoundary component.

The root ErrorBoundary export handles thrown responses and errors if no other nested error boundary has handled them yet. Both errors and thrown responses bubble upward through the route hierarchy.

Then, you learned that error boundaries do not have access to loader data. It is important not to render any components in the boundaries that access the useLoaderData hook.

Using error boundaries makes the application more resilient toward errors. Tight error boundaries keep parts of our application functional if an unexpected error only affects a nested route module.

In the next chapter, we will throw some more responses – 401 responses, to be precise – as we implement an authentication flow and learn more about state management with Remix.

Further reading

You can find a list of all HTTP status codes on MDN: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status.

If you want to learn more about exception and error handling, I recommend that you check out Shawn Wang's (@swyx) blog post Errors Are Not Exceptions: https://www.swyx.io/errors-not-exceptions.

You can find more information about the ErrorBoundary route module export in the Remix documentation: https://remix.run/docs/en/2/route/error-boundary.

The Remix docs also contain a guide with more information about not-found error handling, which you can find here: https://remix.run/docs/en/2/guides/not-found.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Full Stack Web Development with Remix
Published in: Nov 2023Publisher: PacktISBN-13: 9781801075299
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Author (1)

author image
Andre Landgraf

Andre is a full stack developer from Germany. He graduated with an MS in Information Systems from the Technical University of Munich and was also awarded an MS in Computer Science from Sofia University in Palo Alto. Andre currently lives in Cupertino, California, and he works as a Software Engineer at LinkedIn. Andre loves learning, writing, and speaking about all things web. In his free time, he tutors aspiring developers and builds for the web.
Read more about Andre Landgraf