Add backend log management

This commit is contained in:
inman
2026-06-03 11:49:45 +08:00
parent 13ddc66cfe
commit fb0229ba06
14 changed files with 804 additions and 2 deletions

View File

@@ -1,11 +1,30 @@
import { NextResponse } from "next/server";
import { recordAppLog } from "@/lib/server/log-manager";
export function jsonOk<T>(payload: T, init?: ResponseInit) {
return NextResponse.json(payload, init);
}
export function jsonError(error: unknown, status = 400) {
export type JsonErrorOptions = {
request?: Request;
source?: string;
details?: unknown;
logClientErrors?: boolean;
};
export async function jsonError(error: unknown, status = 400, options: JsonErrorOptions = {}) {
const resolvedStatus = statusFromError(error) || status;
if (resolvedStatus >= 500 || options.logClientErrors) {
await recordAppLog({
level: resolvedStatus >= 500 ? "error" : "warning",
source: options.source || "api",
message: error instanceof Error ? error.message : String(error),
error,
status: resolvedStatus,
request: options.request,
details: options.details
}).catch(() => undefined);
}
return NextResponse.json({
error: error instanceof Error ? error.message : String(error)
}, { status: resolvedStatus });