import type { ErrorHandler } from "hono"; import type { Logger } from "pino"; import { CoreError } from "@great-agent/agent-core"; import { ZodError } from "zod"; export function createErrorHandler(logger: Logger): ErrorHandler { return (error, context) => { const requestId = context.get("requestId") ?? crypto.randomUUID(); if (error instanceof ZodError) { return context.json( { error: { code: "REQUEST_INVALID", message: "请求内容无效", requestId, }, }, 400, ); } if (error instanceof CoreError) { const status = error.code === "CONVERSATION_NOT_FOUND" || error.code === "PROJECT_NOT_FOUND" ? 404 : error.code === "PROJECT_RUN_ACTIVE" ? 409 : 400; return context.json( { error: { code: error.code, message: error.message, requestId } }, status, ); } logger.error({ error, requestId }, "请求处理失败"); return context.json( { error: { code: "INTERNAL_ERROR", message: "服务暂时不可用", requestId, }, }, 500, ); }; }