Next.jsMedium
How do you handle errors in API routes?
Wrap handler logic in try/catch, map known failures (validation, not found, conflicts, auth) to the right status codes with a consistent JSON error shape, log unexpected errors on the server, and return a generic 500 without leaking internals. Use onRequestError in instrumentation.ts to report unhandled errors centrally.
Status codes
- 400 malformed input (bad JSON), 422 valid JSON that fails validation.
- 401 not authenticated, 403 authenticated but not allowed.
- 404 resource missing, 405 wrong method (automatic in Route Handlers).
- 409 conflict (duplicate email), 429 rate limited.
- 500 unexpected server error, 502/503/504 upstream or availability problems.
Patterns
- Custom error classes:
class HttpError extends Error { status }, thrown from services and converted once in a wrapper. - Wrapper function:
withErrors(handler)catches everything, convertsHttpErrorandZodError, and logs the rest. - Consistent shape:
{ error: { code: "NOT_FOUND", message: "..." } }, so clients can handle errors generically. - Correlation ID: include a request ID in the response and logs.
What not to do
- Return
error.messagefrom database or library errors to the client; it can expose SQL, paths or secrets. - Return 200 with
{ success: false }; status codes matter for caches, monitoring and clients. - Swallow errors silently.
Observability
instrumentation.ts can export onRequestError(err, request, context), called for errors in Route Handlers, Server Components, Server Functions and Proxy. Forward them to Sentry, Datadog or OpenTelemetry.
Code example
tsx
1// lib/http.ts2import { ZodError } from "zod";34export class HttpError extends Error {5 constructor(public status: number, public code: string, message: string) {6 super(message);7 }8}910export function withErrors<C>(handler: (req: Request, ctx: C) => Promise<Response>) {11 return async (req: Request, ctx: C) => {12 try {13 return await handler(req, ctx);14 } catch (err) {15 if (err instanceof HttpError) {16 return Response.json({ error: { code: err.code, message: err.message } }, { status: err.status });17 }18 if (err instanceof ZodError) {19 return Response.json({ error: { code: "VALIDATION", issues: err.issues } }, { status: 422 });20 }21 const id = crypto.randomUUID();22 console.error(`[${id}]`, err); // full details stay on the server23 return Response.json({ error: { code: "INTERNAL", message: "Something went wrong", id } }, { status: 500 });24 }25 };26}2728// app/api/orders/[id]/route.ts29// export const GET = withErrors(async (_req, ctx: RouteContext<"/api/orders/[id]">) => {30// const order = await db.order.findUnique({ where: { id: (await ctx.params).id } });31// if (!order) throw new HttpError(404, "NOT_FOUND", "Order not found");32// return Response.json(order);33// });
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.