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...