1 const STATUS_NAMES: Record<number, string> = {
2 400: "BadRequest",
3 401: "Unauthorized",
4 403: "Forbidden",
5 404: "NotFound",
6 405: "MethodNotAllowed",
7 422: "UnprocessableEntity",
8 500: "InternalServerError",
9 }
10
11 export type RouteErrorBody = {
12 error: {
13 status: number
14 name: string
15 message: string
16 }
17 }
18
19 /**
20 * Error thrown by {@link throwErrorResponse}. It carries the HTTP status and
21 * message that {@link withRouteErrorHandling} turns into a JSON response.
22 */
23 export class RouteError extends Error {
24 readonly status: number
25 readonly errorName: string
26
27 constructor(status: number, message: string, name?: string) {
28 super(message)
29 this.status = status
30 this.errorName = name ?? STATUS_NAMES[status] ?? "Error"
31 }
32
33 get body(): RouteErrorBody {
34 return {
35 error: {
36 status: this.status,
37 name: this.errorName,
38 message: this.message,
39 },
40 }
41 }
42
43 toResponse(): Response {
44 return new Response(JSON.stringify(this.body), {
45 status: this.status,
46 headers: {
47 "Content-Type": "application/json",
48 },
49 })
50 }
51 }
52
53 /**
54 * Throws an HTTP error from anywhere inside a route handler (or a helper it
55 * calls). The handler — or the outermost function in its call stack — must be
56 * wrapped in {@link withRouteErrorHandling}, which converts the thrown error
57 * into a JSON response of the shape:
58 *
59 * ```json
60 * { "error": { "status": 404, "name": "NotFound", "message": "..." } }
61 * ```
62 */
63 export function throwErrorResponse(
64 status: number,
65 message: string,
66 name?: string
67 ): never {
68 throw new RouteError(status, message, name)
69 }
70
71 /**
72 * Wraps a route handler so that:
73 *
74 * - errors from {@link throwErrorResponse} become JSON responses with their
75 * status.
76 * - any other unexpected error becomes a `500` JSON response instead of the
77 * framework's HTML error page.
78 *
79 * Only use it on handlers that report errors by throwing. Handlers that rely on
80 * `notFound()` / `redirect()` must stay unwrapped, since those work by throwing
81 * too and this wrapper would swallow them into a 500.
82 *
83 * ```ts
84 * export const GET = withRouteErrorHandling(async (req: NextRequest) => {
85 * const spec = await loadSpec()
86 * if (!spec) {
87 * throwErrorResponse(404, "Spec not found")
88 * }
89 * return new Response(spec)
90 * })
91 * ```
92 */
93 export function withRouteErrorHandling<
94 TArgs extends unknown[],
95 TResponse extends Response,
96 >(
97 handler: (...args: TArgs) => Promise<TResponse>
98 ): (...args: TArgs) => Promise<Response> {
99 return async (...args: TArgs) => {
100 try {
101 return await handler(...args)
102 } catch (error) {
103 if (error instanceof RouteError) {
104 return error.toResponse()
105 }
106
107 console.error(error)
108
109 return new RouteError(
110 500,
111 error instanceof Error ? error.message : "Unexpected error"
112 ).toResponse()
113 }
114 }
115 }