fix: 用户名唯一性竞态处理 + 密码长度上限 + JSON.parse 安全

- #6: register/user PUT 捕获 P2002 返回 409,apiHandler 全局兜底
- #8: GET /api/user 的 JSON.parse(preferences) 加 try/catch 防崩溃
- #12: 密码校验加 128 字符上限防 DoS
- #29: ApiError.name 设为 "ApiError" 便于调试
This commit is contained in:
2026-02-26 20:14:02 +08:00
parent 6488c19172
commit 9c7f18e0fa
4 changed files with 57 additions and 27 deletions
+11
View File
@@ -1,4 +1,5 @@
import { NextRequest, NextResponse } from "next/server";
import { Prisma } from "@prisma/client";
import { prisma } from "@/lib/prisma";
export class ApiError extends Error {
@@ -7,6 +8,7 @@ export class ApiError extends Error {
public status: number = 400,
) {
super(message);
this.name = "ApiError";
}
}
@@ -45,6 +47,15 @@ export function apiHandler(handler: RouteHandler): RouteHandler {
if (e instanceof ApiError) {
return NextResponse.json({ error: e.message }, { status: e.status });
}
if (
e instanceof Prisma.PrismaClientKnownRequestError &&
e.code === "P2002"
) {
return NextResponse.json(
{ error: "该记录已存在或值已被占用" },
{ status: 409 },
);
}
console.error(`[API ${req.method} ${req.nextUrl.pathname}]`, e);
return NextResponse.json({ error: "操作失败" }, { status: 500 });
}