1import { err } from "../env.ts";23export class ApiError extends Error {4 readonly status: number;56 constructor(7 status: number,8 message: string,9 options?: ErrorOptions,10 ) {11 super(message, options);12 this.name = "ApiError";13 this.status = status;14 }15}1617export async function readJson<T>(request: Request): Promise<T> {18 try {19 return await request.json<T>();20 } catch (cause) {21 throw new ApiError(400, "invalid JSON body", { cause });22 }23}2425export async function clientInput<T>(26 operation: () => T | Promise<T>,27): Promise<T> {28 try {29 return await operation();30 } catch (cause) {31 const message = cause instanceof Error ? cause.message : "invalid request";32 throw new ApiError(400, message, { cause });33 }34}3536export function apiErrorResponse(error: unknown, request: Request, url: URL): Response {37 if (error instanceof ApiError) return err(error.message, error.status);38 console.error({39 event: "api.unhandled_error",40 method: request.method,41 path: url.pathname,42 error: error instanceof Error ? error.message : String(error),43 });44 return err("internal error", 500);45}