|
| 1 | +import { NextResponse } from 'next/server'; |
| 2 | +import { ValidationError } from '@/utils/validation/preferences-validation'; |
| 3 | +import type { ApiErrorCode } from '@/lib/api/types'; |
| 4 | + |
| 5 | +type KnownCode = Extract<ApiErrorCode, 'UNAUTHORIZED' | 'VALIDATION_ERROR' | 'NOT_FOUND' | 'INTERNAL_ERROR'>; |
| 6 | + |
| 7 | +export class ApiRouteError extends Error { |
| 8 | + readonly status: number; |
| 9 | + readonly code: KnownCode; |
| 10 | + |
| 11 | + constructor(status: number, code: KnownCode, message: string) { |
| 12 | + super(message); |
| 13 | + this.status = status; |
| 14 | + this.code = code; |
| 15 | + this.name = 'ApiRouteError'; |
| 16 | + } |
| 17 | +} |
| 18 | + |
| 19 | +type Handler<TContext = unknown> = ( |
| 20 | + request: Request, |
| 21 | + context: TContext |
| 22 | +) => Promise<Response> | Response; |
| 23 | + |
| 24 | +function getRequestId(request: Request): string { |
| 25 | + return request.headers.get('x-request-id') ?? crypto.randomUUID(); |
| 26 | +} |
| 27 | + |
| 28 | +function mapError(error: unknown): ApiRouteError { |
| 29 | + if (error instanceof ApiRouteError) { |
| 30 | + return error; |
| 31 | + } |
| 32 | + |
| 33 | + if (error instanceof Response) { |
| 34 | + if (error.status === 400) return new ApiRouteError(400, 'VALIDATION_ERROR', 'Invalid request'); |
| 35 | + if (error.status === 401) return new ApiRouteError(401, 'UNAUTHORIZED', 'Unauthorized'); |
| 36 | + if (error.status === 404) return new ApiRouteError(404, 'NOT_FOUND', 'Resource not found'); |
| 37 | + return new ApiRouteError(error.status || 500, 'INTERNAL_ERROR', 'Internal server error'); |
| 38 | + } |
| 39 | + |
| 40 | + if (error instanceof ValidationError) { |
| 41 | + return new ApiRouteError(400, 'VALIDATION_ERROR', error.message); |
| 42 | + } |
| 43 | + |
| 44 | + if ( |
| 45 | + error && |
| 46 | + typeof error === 'object' && |
| 47 | + 'name' in error && |
| 48 | + (error as { name?: string }).name === 'ApiError' && |
| 49 | + 'status' in error && |
| 50 | + typeof (error as { status?: unknown }).status === 'number' |
| 51 | + ) { |
| 52 | + const status = (error as { status: number }).status; |
| 53 | + const message = |
| 54 | + 'message' in error && typeof (error as { message?: unknown }).message === 'string' |
| 55 | + ? (error as { message: string }).message |
| 56 | + : 'Request failed'; |
| 57 | + |
| 58 | + if (status === 400) return new ApiRouteError(400, 'VALIDATION_ERROR', message); |
| 59 | + if (status === 401) return new ApiRouteError(401, 'UNAUTHORIZED', message); |
| 60 | + if (status === 404) return new ApiRouteError(404, 'NOT_FOUND', message); |
| 61 | + return new ApiRouteError(status, 'INTERNAL_ERROR', 'Internal server error'); |
| 62 | + } |
| 63 | + |
| 64 | + return new ApiRouteError(500, 'INTERNAL_ERROR', 'Internal server error'); |
| 65 | +} |
| 66 | + |
| 67 | +export function withApiErrorHandler<TContext = unknown>(handler: Handler<TContext>) { |
| 68 | + return async function wrappedHandler(request: Request, context: TContext): Promise<Response> { |
| 69 | + const requestId = getRequestId(request); |
| 70 | + const url = new URL(request.url); |
| 71 | + const path = url.pathname; |
| 72 | + const method = request.method; |
| 73 | + |
| 74 | + try { |
| 75 | + const response = await handler(request, context); |
| 76 | + response.headers.set('x-request-id', requestId); |
| 77 | + return response; |
| 78 | + } catch (error) { |
| 79 | + const mapped = mapError(error); |
| 80 | + |
| 81 | + if (mapped.code === 'INTERNAL_ERROR') { |
| 82 | + console.error('[api-error]', { requestId, path, method, error }); |
| 83 | + } else { |
| 84 | + console.warn('[api-error]', { |
| 85 | + requestId, |
| 86 | + path, |
| 87 | + method, |
| 88 | + status: mapped.status, |
| 89 | + code: mapped.code, |
| 90 | + message: mapped.message, |
| 91 | + }); |
| 92 | + } |
| 93 | + |
| 94 | + return NextResponse.json( |
| 95 | + { |
| 96 | + success: false as const, |
| 97 | + error: { |
| 98 | + code: mapped.code, |
| 99 | + message: mapped.message, |
| 100 | + }, |
| 101 | + requestId, |
| 102 | + }, |
| 103 | + { |
| 104 | + status: mapped.status, |
| 105 | + headers: { |
| 106 | + 'x-request-id': requestId, |
| 107 | + }, |
| 108 | + } |
| 109 | + ); |
| 110 | + } |
| 111 | + }; |
| 112 | +} |
0 commit comments