Add the Error Envelope and Request Validation
Every API error has the same JSON shape, validation failures carry field errors, and production hides internals.
Install
npm i @dapplelight/signet-server @dapplelight/signet-lib hono zodInstall the handler
import { getRuntimeEnv } from "@dapplelight/signet-server/env"
import { errorHandler } from "@dapplelight/signet-server/http"
import { Hono } from "hono"
import { sentry } from "./server/sentry"
const app = new Hono()
app.onError(errorHandler({
isProduction: () => getRuntimeEnv().NODE_ENV === "production",
onError: (err, meta) => sentry.captureException(err, meta),
}))isProduction is a function so it is read per request.
Validate input
import { ApiException } from "@dapplelight/signet-server/http"
import { parseBody } from "@dapplelight/signet-server/http/validate"
import { z } from "zod"
import { app } from "../app"
import { allowed, create } from "./store"
const thingSchema = z.object({ name: z.string() })
app.post("/things", async (c) => {
const body = await parseBody(c, thingSchema)
if (!allowed) throw new ApiException(403, "Not allowed", "NOT_IN_HOUSEHOLD")
return c.json(await create(body))
})A bad body is a 400 with details.fieldErrors.
Type the routes for a client
import { zValidator } from "@dapplelight/signet-server/http/validate"
import { Hono } from "hono"
import { z } from "zod"
import { NoteInput, save, get } from "./server/notes"
export const app = new Hono()
.post("/api/notes", zValidator("json", NoteInput), (c) => c.json(save(c.req.valid("json")), 201))
.get("/api/notes/:id", zValidator("param", z.object({ id: z.string() })), (c) => c.json(get(c.req.valid("param").id)))
export type AppType = typeof appRead it in the browser
import { ApiError } from "@dapplelight/signet-lib/api"
import { api } from "./api"
export async function submit(
json: { title: string },
setFieldErrors: (errors: Record<string, string[]>) => void,
) {
try {
await api.api.notes.$post({ json })
} catch (e) {
if (e instanceof ApiError && e.code === "VALIDATION_FAILED") setFieldErrors(e.details?.fieldErrors ?? {})
}
}Branch on code, never on the message.