import { NextRequest, NextResponse } from "next/server"; import { runWithLlmConfig, llmConfigFromHeaders } from "./llm-context"; /** * Structured API error class. * Throw this inside route handlers for controlled error responses. */ export class ApiError extends Error { constructor( public readonly statusCode: number, message: string, ) { super(message); this.name = "ApiError"; } } type RouteHandler = ( request: NextRequest, context?: unknown, ) => Promise | NextResponse; /** * Higher-order function that wraps a Next.js route handler with * consistent error handling. * * - ApiError instances return { error, status } with the specified status code. * - Unknown errors return a generic 500 with the message logged to stderr. */ export function withApiError(handler: RouteHandler): RouteHandler { return async (request: NextRequest, context?: unknown) => // Make the visitor's per-request LLM credentials (x-hf-token / x-hf-model) // available to every `claude` call site for the duration of the handler. runWithLlmConfig(llmConfigFromHeaders(request.headers), async () => { try { return await handler(request, context); } catch (err) { if (err instanceof ApiError) { console.error(`[API ${err.statusCode}] ${request.nextUrl.pathname}: ${err.message}`); return NextResponse.json( { error: err.message, status: err.statusCode }, { status: err.statusCode }, ); } const message = err instanceof Error ? err.message : String(err); const stack = err instanceof Error ? err.stack : undefined; console.error( `[API 500] ${request.nextUrl.pathname}: ${message}`, stack ?? "", ); return NextResponse.json( { error: "Internal server error", status: 500 }, { status: 500 }, ); } }); }