/** * Finding: A-02 (error contract) * * Every API error leaves the server in one shape: RFC 9457 application/problem+json. * The form can map `errors[].path` straight back onto inputs, and support can find the * request in logs from `requestId` without the user ever seeing a stack trace. */ import { ZodError } from "zod"; export type FieldError = { path: string; message: string }; export type Problem = { type: string; title: string; status: number; detail?: string; errors?: FieldError[]; requestId: string; retryAfterSeconds?: number; }; const BASE = "https://www.cynbit.in/problems"; export class HttpProblem extends Error { constructor( public readonly status: number, public readonly slug: string, public readonly title: string, public readonly extras: Partial> = {}, ) { super(title); } } export const Problems = { validation: (errors: FieldError[]) => new HttpProblem(422, "validation", "Some fields need attention", { errors }), payloadTooLarge: () => new HttpProblem(413, "payload-too-large", "That submission is too large"), unsupportedMedia: () => new HttpProblem(415, "unsupported-media-type", "Send the form as JSON"), botCheckFailed: () => new HttpProblem(403, "verification-failed", "We couldn't verify this submission. Refresh and try again"), rateLimited: (retryAfterSeconds: number) => new HttpProblem(429, "rate-limited", "Too many submissions. Try again shortly", { retryAfterSeconds }), idempotencyConflict: () => new HttpProblem(409, "idempotency-conflict", "This request is already being processed"), notFound: (what: string) => new HttpProblem(404, "not-found", `${what} not found`), } as const; export function zodToFieldErrors(err: ZodError): FieldError[] { return err.issues.map((i) => ({ path: i.path.map(String).join("."), message: i.message })); } export function problemResponse(err: unknown, requestId: string): Response { const p: Problem = err instanceof HttpProblem ? { type: `${BASE}/${err.slug}`, title: err.title, status: err.status, requestId, ...err.extras } : err instanceof ZodError ? { type: `${BASE}/validation`, title: "Some fields need attention", status: 422, errors: zodToFieldErrors(err), requestId } : { type: `${BASE}/internal`, title: "Something went wrong on our side. Your data was not saved", status: 500, requestId }; if (p.status >= 500) { // Log the real error server-side only. Never serialise it into the response. console.error(JSON.stringify({ level: "error", requestId, err: err instanceof Error ? { name: err.name, message: err.message, stack: err.stack } : String(err) })); } const headers = new Headers({ "Content-Type": "application/problem+json", "Cache-Control": "no-store", "X-Request-Id": requestId }); if (p.retryAfterSeconds) headers.set("Retry-After", String(p.retryAfterSeconds)); return new Response(JSON.stringify(p), { status: p.status, headers }); }