Yaltopia-FIFA/lib/api/errors.ts
Kirubel-Kibru-Yaltopia 89440985f1
Some checks failed
Deploy to Cloudflare Workers / deploy (push) Has been cancelled
x
2026-05-24 21:46:10 +03:00

37 lines
951 B
TypeScript

import { NextResponse } from "next/server";
export class ApiError extends Error {
constructor(
public status: number,
message: string
) {
super(message);
this.name = "ApiError";
}
}
export function apiSuccess<T>(data: T, status = 200) {
return NextResponse.json({ success: true, data }, { status });
}
export function apiError(error: unknown) {
if (error instanceof ApiError) {
return NextResponse.json(
{ success: false, error: error.message },
{ status: error.status }
);
}
const message =
error instanceof Error ? error.message : "Internal server error";
console.error("[API]", error);
return NextResponse.json({ success: false, error: message }, { status: 500 });
}
export async function parseJson<T>(request: Request): Promise<T> {
try {
return (await request.json()) as T;
} catch {
throw new ApiError(400, "Invalid JSON body");
}
}