How should I handle my errors that might occur in my route.ts in Next.js 14 (app router) using SWR?
Unanswered
African Slender-snouted Crocodil… posted this in #help-forum
African Slender-snouted CrocodileOP
I have the following component:
table.tsx:
Route handler route.ts:
I want to forward the error that happens here
table.tsx:
const fetcher = (url: string) => fetch(url).then((res) => res.json());
export default function Table() {
const { data, error, isLoading } = useSWR(
`/api/product`,
fetcher,
);
if (error) throw new Error("Failed to load products data. ERROR: " + error);
etc. etc. etc.Route handler route.ts:
import { fetchProduct } from "@/components/products/requests/requests";
import { NextRequest } from "next/server";
export async function GET(request: NextRequest) {
// wait for 1s
await new Promise((res) => setTimeout(res, 1000));
// error!
if (Math.random() < 0.4) throw new Error("An error has occurred in ROUTE.TS!");
const product = await fetchProduct('product-slug');
return Response.json(product);
}I want to forward the error that happens here
export async function GET(request: NextRequest)to my calling component <Table /> ... how can I do this?7 Replies
African Slender-snouted CrocodileOP
do I need to catch the error first in my route handler?
Sedge Wren
Yes you need to catch the error and send a NextResponse with status.
African Slender-snouted CrocodileOP
well i forgot to mention that i want my /dashboard/products/error.tsx to handle the error:
in that case I think i will not need the try catch in my route handler, correct?
"use client";
import Error from "@/components/common/components/error";
import { useEffect } from "react";
export default function ErrorPage({
error,
reset,
}: {
error: Error & { digest?: string };
reset: () => void;
}) {
useEffect(() => {
console.error(
`/app/dashboard/products/error.tsx ${error} Error Digest: ${error.digest}`,
);
}, [error]);
return <Error reset={reset} />;
}in that case I think i will not need the try catch in my route handler, correct?
and this is my <Error /> component:
export default function Error({ reset }: { reset: () => void }) {
return (
<div className="grid min-h-full place-items-center bg-theme-app-background px-6 py-12 sm:py-24 lg:px-8">
<div className="text-center">
<p className="text-base font-semibold text-theme-typography-accent">
500
</p>
<h1 className="mt-4 text-3xl font-bold tracking-tight text-theme-typography-heading sm:text-5xl">
Cats on the Keyboard!
</h1>
<p className="mt-6 text-base leading-7 text-theme-typography-paragraph lg:px-60">
Well, this is awkward. Our digital cats decided to paw-sitively rebel
and took an unplanned catnap, causing a little tech mayhem. But
don't fret, we're untangling the yarn of code as we speak!
</p>
<div className="mt-10 flex items-center justify-center gap-x-6">
<button
className="rounded-md bg-theme-button-primary px-3.5 py-2.5 text-sm font-semibold text-white shadow-sm hover:bg-theme-button-primary-hover focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-theme-button-primary-focus-visible"
onClick={reset}
type="button"
>
Retry Meow
</button>
</div>
</div>
</div>
);
}so basically i want Next.js to handle all of my errors
Sedge Wren
are you already using an error.ts file at the parent of layout level or global level? It should show the error then
@African Slender-snouted Crocodile I have the following component:
table.tsx:
const fetcher = (url: string) => fetch(url).then((res) => res.json());
export default function Table() {
const { data, error, isLoading } = useSWR(
`/api/product`,
fetcher,
);
if (error) throw new Error("Failed to load products data. ERROR: " + error);
etc. etc. etc.
Route handler route.ts:
import { fetchProduct } from "@/components/products/requests/requests";
import { NextRequest } from "next/server";
export async function GET(request: NextRequest) {
// wait for 1s
await new Promise((res) => setTimeout(res, 1000));
// error!
if (Math.random() < 0.4) throw new Error("An error has occurred in ROUTE.TS!");
const product = await fetchProduct('product-slug');
return Response.json(product);
}
I want to forward the error that happens here `export async function GET(request: NextRequest)`to my calling component `<Table />` ... how can I do this?
errors thrown in route.ts files automatically becomes a 500 empty response. the error message is not sent to the client.
route.ts does not interact with error.js. you need to use [suspense mode](https://swr.vercel.app/docs/suspense) of swr to trigger suspense and error boundaries.
route.ts does not interact with error.js. you need to use [suspense mode](https://swr.vercel.app/docs/suspense) of swr to trigger suspense and error boundaries.