refactor: 引入 apiHandler + ApiError,消除 20 个路由的 try/catch 样板

- 新增 src/lib/api.ts:ApiError 错误类 + apiHandler 统一包装器
- 20 个 API 路由统一使用 apiHandler,删除重复的 try/catch 块
- 验证错误改用 throw new ApiError(),减少嵌套层级
- join/manage 路由的错误码映射改为直接抛出 ApiError
- 删除已无引用的 errorResponse 辅助函数
- 净减 273 行代码
This commit is contained in:
2026-02-26 18:08:47 +08:00
parent d4c6da57a1
commit 0595887480
22 changed files with 626 additions and 863 deletions
+36
View File
@@ -0,0 +1,36 @@
import { NextRequest, NextResponse } from "next/server";
export class ApiError extends Error {
constructor(
message: string,
public status: number = 400,
) {
super(message);
}
}
type RouteContext = { params: Promise<Record<string, string>> };
type RouteHandler = (
req: NextRequest,
ctx: RouteContext,
) => Promise<NextResponse>;
/**
* Wraps a Next.js route handler with unified error handling.
* - ApiError instances are converted to JSON responses with matching status codes
* - Unknown errors are logged and returned as 500
*/
export function apiHandler(handler: RouteHandler): RouteHandler {
return async (req, ctx) => {
try {
return await handler(req, ctx);
} catch (e) {
if (e instanceof ApiError) {
return NextResponse.json({ error: e.message }, { status: e.status });
}
console.error(`[API ${req.method} ${req.nextUrl.pathname}]`, e);
return NextResponse.json({ error: "操作失败" }, { status: 500 });
}
};
}