Next.js Discord

Discord Forum

Next.js 14 Middleware - api error handling

Answered
English Mastiff posted this in #help-forum
Open in Discord
English MastiffOP
Is possible to catch errors in middleware that are thrown in route.ts?

Something like below:

middleware.ts
export default async function middleware (req: NextRequest) {
try {
const response = await NextResponse.next();
return response;
} catch (error) {

return NextResponse.json(
{ message : "Example message" },
{ status: 500 }
);
}

route.ts
export async function GET(req: NextRequest, context: any) {
throw new Error("Example error")
}
Answered by joulev
No, not possible.

Uncaught exceptions in route handlers become an empty 500 response (return new Response(null, { status: 500 })). They are not “propagated” to the middleware or other parts of the system.
View full answer

1 Reply