--- title: "Errors" description: "Handle Beignet server and client errors with AppError, ContractError, structured response envelopes, and safeCall." url: "https://www.beignetjs.com/errors" markdown_url: "https://www.beignetjs.com/markdown/errors.md" framework_version: "0.0.65" documentation_scope: "current-checkout" source_revision: "e5b4771b262efbdd036e3a40a514c08d1508316c" source_modified: true --- # Errors This page owns the server-side error story: the app error catalog, `AppError`, cause preservation, and unhandled-error mapping. For handling failed calls on the client with `ContractError`, see [Client](https://www.beignetjs.com/markdown/client.md#error-handling). Use [Error reporting and alerting](https://www.beignetjs.com/markdown/error-reporting.md) for production exception capture and alerting. Error catalogs describe expected application failures; they are not a replacement for production incident reporting. ## Error shape Framework-owned errors use a standard envelope: ```json { "code": "VALIDATION_ERROR", "message": "Invalid request body", "details": { "contract": "todos.create", "method": "POST", "path": "/api/todos", "location": "body", "issues": [ { "path": ["title"], "message": "Required" } ] } } ``` Validation and response-contract diagnostics include the contract name, HTTP method, contract path, and failing location when Beignet can identify them. Some framework-owned errors may also include a top-level `requestId` when your server context exposes one. Route-owned error responses can use any schema declared in `contract.responses`. Using `{ code, message, details? }` for route-owned errors keeps your application errors consistent with framework errors. Framework-owned upload, webhook, payment-webhook, schedule, and outbox-drain routes use the same flat shape. Their operation-specific `code` values are stable for programmatic handling; operation context such as a schedule name is carried in `details` rather than changing the envelope. ## Define an error catalog ```typescript import { createAppError, defineErrors } from "@beignet/core/errors"; import { z } from "zod"; export const errors = defineErrors({ TodoNotFound: { code: "TODO_NOT_FOUND", status: 404, message: "Todo not found", details: z.object({ id: z.string() }), }, Unauthorized: { code: "UNAUTHORIZED", status: 401, message: "You must be signed in", }, Forbidden: { code: "FORBIDDEN", status: 403, message: "You cannot perform this action", }, }); export const appError = createAppError(errors); ``` Declare catalog errors on contracts with `.errors()`. Beignet maps them to the standard `{ code, message, details?, requestId? }` response envelope automatically: ```typescript export const getTodo = todos .get("/api/todos/:id") .responses({ 200: TodoSchema }) .errors({ TodoNotFound: errors.TodoNotFound }); ``` Catalog errors can also be declared on a contract group with `defineContractGroup().errors(...)`. Group errors merge with route-level `.errors(...)`, so contracts carry the union of both; later declarations win when the same catalog key is declared twice. The optional `details` schema types `appError()` calls and client-side `error.details` after narrowing by catalog code. Beignet does not automatically redact route-owned error details. Treat `message` and `details` as public client response data. Put stable IDs, field names, ability names, or operation names there; keep stack traces, provider errors, SQL, secrets, tokens, PHI, private content, and raw request bodies in `cause`, logs, or error reporting instead. ## Throw `AppError` Throw `AppError` from use cases, handlers, or domain/core/application code when you want a typed HTTP failure. ```typescript import { defineRouteGroup } from "@/lib/routes"; import { useCase } from "@/lib/use-case"; export const getTodoUseCase = useCase .query("todos.get") .input(GetTodoInputSchema) .output(TodoSchema) .run(async ({ ctx, input }) => { const todo = await ctx.ports.todos.findById(input.id); if (!todo) { throw appError("TodoNotFound", { details: { id: input.id } }); } return todo; }); export const todoRoutes = defineRouteGroup({ name: "todos", routes: [{ contract: getTodo, useCase: getTodoUseCase }], }); ``` `AppError` instances thrown by a bound use case or a route handler are route-owned. If the route declares response schemas, the generated response must match the schema for that status. ## Preserve causes Use `cause` for debugging without exposing internal errors to clients. ```typescript import { AppError, httpErrors } from "@beignet/core/errors"; try { await db.query(...); } catch (dbError) { throw new AppError( httpErrors.InternalServerError, { operation: "todos.query" }, undefined, { cause: dbError }, ); } ``` Helper-created `AppError`s support the same option: ```typescript throw appError("InternalServerError", { details: { operation: "todos.query" }, cause: dbError, }); ``` The `cause` is available via `error.cause` and is never exposed to the client by Beignet. `details` and `message` are public response fields when the error crosses the HTTP boundary, so only include values that are safe for clients. ## Set response headers on errors Pass `headers` when an error response should carry standard HTTP headers, such as `Retry-After` on a 429. The server merges them onto the mapped response; like `details`, headers are public response data. ```typescript import { AppError, httpErrors } from "@beignet/core/errors"; throw new AppError( httpErrors.TooManyRequests, { retryAfterSeconds: 30 }, undefined, { headers: { "Retry-After": "30" } }, ); ``` Helper-created errors accept the same option: `appError("Forbidden", { headers: { ... } })`. The framework's own `createRateLimitHooks` denials use this to set `Retry-After` automatically whenever the limiter reports a reset time. ## Observe and map unhandled errors Use the server's `onCaughtError` option for logging, metrics, and tracing: it observes caught failures without changing response behavior. The server-level `mapUnhandledError` callback maps unknown or otherwise unhandled exceptions after declared `AppError` instances are auto-mapped. ```typescript onCaughtError: ({ err, req, ctx }) => { console.error("Caught error:", err); console.error("Request:", req.method, new URL(req.url).pathname); console.error("Request ID:", ctx?.requestId); }, mapUnhandledError: ({ ctx }) => { return { status: 500, body: { code: "INTERNAL_SERVER_ERROR", message: "Internal server error", requestId: ctx?.requestId, }, }; }, ``` `mapUnhandledError` responses are framework-owned; see [Request lifecycle](https://www.beignetjs.com/markdown/request-lifecycle.md#response-ownership) for the ownership taxonomy. When `mapUnhandledError` is omitted, Beignet's fallback 500 includes the original error message and stack only when `NODE_ENV` is explicitly `development` or `test`. Unset, staging, production, and other environment values receive only the stable internal-error envelope and request ID. ## Errors on the client Catalog errors cross the HTTP boundary as the same `{ code, message, details?, requestId? }` envelope, and framework-owned responses carry the `x-beignet-error-owner: framework` header so clients can tell them apart from route-owned errors with the same status. On the client they surface as `ContractError`, with `isError(...)` narrowing by catalog code, status, or source, and `safeCall()` for result-style handling. See [Client](https://www.beignetjs.com/markdown/client.md#error-handling) for the full client-side story. ## Map errors to UI Use `contractErrorMessage` from `@beignet/core/client` to turn a failed call into user-facing copy. Non-`ContractError` values return the fallback, client-side input validation failures return a generic "check the highlighted fields" message, and catalog codes can override copy per call site: ```typescript import { contractErrorMessage } from "@beignet/core/client"; const message = contractErrorMessage(error, "Could not update profile.", { HANDLE_UNAVAILABLE: "That handle is already taken.", }); ``` For React Hook Form, `rootFormError` from `@beignet/react-hook-form` wraps the same mapping in the `form.setError("root", ...)` shape; see [React Hook Form](https://www.beignetjs.com/markdown/react-hook-form.md). For TanStack Form, `serverErrorMap` from `@beignet/react-form` wraps it in the `{ onServer }` shape that `form.setErrorMap(...)` accepts; see [TanStack Form](https://www.beignetjs.com/markdown/react-form.md). Use catalog codes for product-specific copy while keeping the default framework message for ordinary route-owned errors.