File size: 1,935 Bytes
9580dce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
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> | 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 },
        );
      }
    });
}