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:
@@ -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 });
|
||||
}
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user