Alright this one’s going to be quick. no bs. I was working on a Next.js project and needed a way to handle API Route Errors Globally. Similar to Express in Node.js.
This is what I’ve come up with and it works wonders for my setup.
1. We create a handler function that will take multiple handlers and run them one by one.
import { ApiError } from "next/dist/server/api-utils"; import { NextResponse, NextRequest } from "next/server";
export const custom_middleware = (...handlers: Function[]) => async (req: NextRequest, res: NextResponse) => { try { for (const handler of handlers) { await handler(req, res); } } catch (error) { if (error instanceof ApiError) { return NextResponse.json( { message: error.message }, { status: error.statusCode } ); } else { /// Log server errors using winston or your preferred logger console.log(error); return NextResponse.json( { message: "Server died for some reason" }, { status: 500 } ); } } };
2. Now we can add it to a route
app/api/ping/route.ts
import { custom_middleware } from "@/app/lib/server/middleware"; import { ApiError } from "next/dist/server/api-utils"; import { NextRequest, NextResponse } from "next/server";