Spaces:
Runtime error
Runtime error
File size: 1,421 Bytes
ad79323 | 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 61 62 63 64 65 66 | import { Prisma } from "@prisma/client";
import { NextResponse } from "next/server";
import { ZodError } from "zod";
export class AppError extends Error {
status: number;
details?: unknown;
constructor(message: string, status = 400, details?: unknown) {
super(message);
this.name = "AppError";
this.status = status;
this.details = details;
}
}
export function isPrismaUniqueConstraintError(
error: unknown,
field?: string,
): boolean {
if (!(error instanceof Prisma.PrismaClientKnownRequestError)) {
return false;
}
if (error.code !== "P2002") {
return false;
}
if (!field) {
return true;
}
const target = error.meta?.target;
return Array.isArray(target) ? target.includes(field) : false;
}
export function createRouteErrorResponse(
error: unknown,
fallbackMessage = "حصل خطأ، حاول تاني بعد شوية.",
) {
if (error instanceof ZodError) {
return NextResponse.json(
{
message: "البيانات اللي دخلتها محتاجة مراجعة.",
errors: error.flatten(),
},
{ status: 400 },
);
}
if (error instanceof AppError) {
return NextResponse.json(
{
message: error.message,
details: error.details,
},
{ status: error.status },
);
}
console.error(error);
return NextResponse.json({ message: fallbackMessage }, { status: 500 });
}
|