| 1 | import type { Context } from "hono"; |
| 2 | import { HTTPException } from "hono/http-exception"; |
| 3 | import type { ContentfulStatusCode } from "hono/utils/http-status"; |
| 4 | import type { AppEnv } from "../env"; |
| 5 | |
| 6 | // A client-safe error: the code/message pair is sent verbatim to the caller, so |
| 7 | // never put internal detail in here. |
| 8 | export class ApiError extends Error { |
| 9 | constructor( |
| 10 | public readonly status: ContentfulStatusCode, |
| 11 | public readonly code: string, |
| 12 | message: string, |
| 13 | ) { |
| 14 | super(message); |
| 15 | this.name = "ApiError"; |
| 16 | } |
| 17 | } |
| 18 | |
| 19 | export function errorHandler(err: Error, c: Context<AppEnv>): Response { |
| 20 | if (err instanceof ApiError) { |
| 21 | return c.json({ error: { code: err.code, message: err.message } }, err.status); |
| 22 | } |
| 23 | if (err instanceof SyntaxError) { |
| 24 | return c.json({ error: { code: "invalid_json", message: "Request body must be valid JSON." } }, 400); |
| 25 | } |
| 26 | if (err instanceof HTTPException) { |
| 27 | return err.getResponse(); |
| 28 | } |
| 29 | console.error("unhandled error:", err); |
| 30 | return c.json({ error: { code: "internal", message: "Something went wrong." } }, 500); |
| 31 | } |
| 32 | |
| 33 | export function notFoundHandler(c: Context<AppEnv>): Response { |
| 34 | return c.json({ error: { code: "not_found", message: "Not found." } }, 404); |
| 35 | } |
| 36 |