Files
photoreport/apps/api/src/lib/errors.ts
T
sparkandClaude Opus 5.5 64d52fc691
ci / rust (push) Successful in 15m6s
ci / typescript (push) Successful in 18m21s
Errors to errors.bitreport.pt from API, worker, app, desktop, sites and print agent
API and worker report error log lines, unhandled 5xx and crashes to the hub with the
photoreport ingest key (ERROR_REPORTING_TOKEN); browsers (app, desktop webview, sites),
Next server renders and the print agent send through POST /v1/client-errors so the key
stays on the server. Repeats folded, rate-limited. docs/errors.md.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
2026-10-14 19:32:54 +01:00

39 lines
1.7 KiB
TypeScript

import type { FastifyError, FastifyInstance } from "fastify";
import { ZodError } from "zod";
/** Errors the API returns on purpose. Anything else is logged and answered as a 500. */
export class AppError extends Error {
constructor(
readonly status: number,
readonly code: string,
message?: string,
) {
super(message ?? code);
}
}
export const badRequest = (code: string, message?: string) => new AppError(400, code, message);
export const unauthorized = (code = "unauthorized") => new AppError(401, code);
export const forbidden = (code = "forbidden") => new AppError(403, code);
export const notFound = (code = "not_found") => new AppError(404, code);
export const conflict = (code: string) => new AppError(409, code);
export function registerErrorHandler(app: FastifyInstance): void {
app.setErrorHandler((err: FastifyError | AppError | ZodError, req, reply) => {
if (err instanceof AppError) {
return reply.code(err.status).send({ error: err.code, message: err.message });
}
if (err instanceof ZodError) {
return reply.code(400).send({ error: "invalid_request", issues: err.issues });
}
if ("statusCode" in err && err.statusCode === 429) {
return reply.code(429).send({ error: "rate_limited", message: err.message });
}
if ("statusCode" in err && typeof err.statusCode === "number" && err.statusCode < 500) {
return reply.code(err.statusCode).send({ error: err.code ?? "request_error", message: err.message });
}
req.log.error({ err, method: req.method, route: req.routeOptions?.url ?? req.url.split("?")[0] }, "unhandled error");
return reply.code(500).send({ error: "internal_error" });
});
}