14. Errors #
@civility/errors is the shared error vocabulary for Civility: the canonical
error-code registry, the CivilityApiError client-side error class, and the
success/error response envelopes returned by every server route.
This feature owns the error taxonomy and wire envelopes. It does not own the
production of those errors — the server-side ok/err route helpers and the
global onError handler live in §13 (Server); client-side error dispatch
(CivilityApiError production, SyncErrorEvent) lives in §3 (Sync). This
feature defines the shapes both sides agree on.
14.1 Purpose & Architecture #
@civility/errors lives in its own package so both client code (@civility/cloud)
and server code (@civility/hono) can depend on one set of error codes and
envelopes without depending on each other. Apps consume it transitively through
@civility/cloud.
The package is small and safe to import from browser, Deno, workers, and Node.
@civility/errors
├── mod.ts
├── lib/
│ ├── codes.ts → ErrorDomain, KnownErrorCode, ErrorCode, ErrorCodes registry, domainOf, httpStatusFor
│ ├── error.ts → CivilityApiError class + CivilityApiErrorInit
│ └── response.ts → SuccessResponse, ErrorResponse, ApiEnvelope, ok(), err(), isErrorResponse()
└── docs.ts → code descriptions + README table generator (build-time only, not exported)
14.2 Design Principles #
- Zero runtime deps, one wire format. Every Civility server route returns
SuccessResponse<T> | ErrorResponse(§14.5). There is no ad-hoc{ error: string }anywhere in the system. - Structured errors on the client.
CivilityApiError(§14.4) carries a stablecodeso apps branch on meaning, not onmessage.includes('...'). - Codes are exhaustive but extensible.
ErrorCodeslists the canonical set with default HTTP statuses. The publicErrorCodetype unions the known literals with${ErrorDomain}.${string}, so package-specific codes type-check without a registry update. - HTTP status is derivable.
httpStatusFor(code)returns the canonical status for a known code, or500for unknown codes. Callers may override (e.g. a 201 on create) but rarely need to. detailsisunknown. The envelope carries an optionaldetailsfield whose shape is domain-specific. Consumers narrow it by branching oncodefirst.- One class, not an error hierarchy. Rather than
AuthError extends CivilityApiError,QuotaError extends CivilityApiError, etc., there is a single class with adomaingetter. Subclasses would force every package-of-use to depend on@civility/errorsjust to doinstanceof, defeating the point of a shared vocabulary.
14.3 Error Code Registry #
An error code is a domain-prefixed string, domain.specifier, e.g.
auth.invalid_credentials. Each canonical code maps to a default HTTP status.
14.3.1 Domains #
type ErrorDomain =
| 'auth' // credentials, sessions, tokens
| 'sync' // push/pull/app lifecycle on the server side
| 'validation' // schema / request-shape failures
| 'quota' // storage, rate limits, size caps
| 'permission' // authz scopes and grants
| 'blob' // binary transfer and addressing
| 'billing' // billing / subscription state
| 'sharing' // cross-app data access
| 'internal' // catch-all for bugs / unexpected server state
billing currently has no canonical registry entries — it exists as a domain
so billing.* codes emitted inline still resolve a domain and fall back to a
500 status.
14.3.2 Registry shape & types #
const ErrorCodes: Record<KnownErrorCode, { httpStatus: number }> = {
'auth.invalid_credentials': { httpStatus: 401 },
// ... full list below
}
type ErrorCode = KnownErrorCode | `${ErrorDomain}.${string}`
KnownErrorCode is declared as an explicit literal union (not
keyof typeof ErrorCodes), and the Record<KnownErrorCode, …> annotation on
ErrorCodes keeps the two lists in sync — TS rejects any extra or missing key
on either side. The explicit union is required because JSR's no-slow-types
rule wants explicit types on exported symbols, and it gives editors direct
autocomplete of the literals.
14.3.3 Canonical codes #
Canonical list is generated from code in-repo.
Notable status choices:
sync.network_erroruseshttpStatus: 0— a client-only code emitted before any response is received.0signals "no HTTP status" to consumers.sync.request_timeoutis408(client-side abort), not504(upstream gateway timeout).blob.url_unavailableis500: the server could not produce a signed/CDN URL, which is a server-side configuration failure.sharing.not_supportedis501(Not Implemented): the endpoint exists but cross-app sharing is unavailable for this app/backend combination.
14.3.4 Helpers #
function domainOf(code: ErrorCode): ErrorDomain // leading segment before the first '.'
function httpStatusFor(code: ErrorCode): number // registry status, or 500 if unknown
14.3.5 Adding a code #
- Add the literal to the
KnownErrorCodeunion incodes.ts. - Add the entry to
ErrorCodeswith its default HTTP status. - Add a one-line description to
ErrorCodeDescriptionsindocs.ts(TS rejects a missing key) and rundeno task docsto regenerate the README table (§14.3.6). - If the default status is unusual (not 400/401/403/404/409/422/429/413/500), document the reason in a comment.
Package-specific codes that only need to exist briefly — e.g. an app-owner's
ad-hoc error — can be emitted inline as err('sync.my_custom', '...') and skip
the registry. They lose autocomplete but still type-check via the
${ErrorDomain}.${string} fallback, and resolve to 500 from httpStatusFor.
14.3.6 Registry → README generation #
The error-code table in the package README.md is generated, not hand-edited.
docs.ts holds a ErrorCodeDescriptions: Record<KnownErrorCode, string> map —
the Record annotation keeps it in lockstep with the registry the same way
ErrorCodes itself is — plus a renderer that writes the table between
<!-- error-codes:start … --> / <!-- error-codes:end --> markers.
deno task docsrewrites the README;deno task docs:checkverifies it.- A test (
__tests__/docs.test.ts) fails the suite whenever the README drifts fromcodes.ts, so the sync is enforced by CI, not convention. - The generated table is padded to
deno fmt's Markdown style so a format pass leaves it unchanged. docs.tsis deliberately not exported frommod.ts— descriptions are docs, and keeping them out of the export graph keeps them out of app bundles.
14.4 CivilityApiError #
The structured error class produced on the client. Parsed from a server
ErrorResponse, or constructed directly when a network/timeout error occurs
before any response is received.
interface CivilityApiErrorInit {
code: ErrorCode
message: string
httpStatus: number
messageKey?: string
details?: unknown
cause?: unknown
}
class CivilityApiError extends Error {
readonly code: ErrorCode
readonly httpStatus: number
readonly messageKey?: string // i18n key for this message variant, when sent
readonly details?: unknown
get domain(): ErrorDomain // domainOf(this.code)
static fromResponse(body: ErrorResponse, httpStatus: number): CivilityApiError
}
nameis set to'CivilityApiError'.causeis forwarded toError's standardcauseoption (only when defined).@civility/clouduses this to attach the underlyingTypeErroron afetch()failure, or the originalAbortErroron a timeout.
Why an instance, not a plain object: error instanceof CivilityApiError is
the canonical way to recognise a structured error in app try/catch blocks that
catch multiple error types; stack traces survive for useful logs; and it is
still JSON-serialisable via { code, httpStatus, message, details } for
telemetry.
14.4.1 fromResponse #
CivilityApiError.fromResponse(body: ErrorResponse, httpStatus: number)
Used by SyncApi (§3) after isErrorResponse(body) has confirmed the body
shape. The httpStatus argument comes from Response.status — the body alone
is not trusted for status because it could be forged or mangled by a proxy,
whereas the HTTP status always reflects what happened at the transport layer.
messageKey is copied only when it is a string — the guard (§14.5.2) doesn't
check optional fields, so a mangled messageKey degrades to "absent" rather
than rejecting an otherwise-valid envelope.
14.5 Response Envelopes #
Standardised JSON shapes returned by every Civility server route, and what the client parses.
interface SuccessResponse<T> {
status: 'success'
message: string
data: T
}
interface ErrorResponse {
status: 'error'
code: ErrorCode
message: string
messageKey?: string // stable i18n key for this message variant
details?: unknown // domain-specific; treat as unknown until narrowed by code
}
type ApiEnvelope<T> = SuccessResponse<T> | ErrorResponse
messageKey exists for localisation: code is the coarse branch key, but one
code may be emitted with several distinct messages (e.g. auth.invite_invalid
for expired vs. revoked vs. already-used). A route that wants clients to
localise a specific variant sends a stable messageKey alongside the English
message; clients without a translation fall back to message. The field is
additive and optional, so the wire protocol is unchanged for routes and clients
that ignore it.
14.5.1 Builders #
function ok<T>(data: T, message = 'ok'): SuccessResponse<T>
function err(
code: ErrorCode,
message: string,
details?: unknown,
messageKey?: string,
): ErrorResponse
ok()always includesmessage, defaulting to'ok'— keeping it non-optional simplifies the consumer's type narrowing.err()setsdetailsandmessageKeyonly when they are defined, avoiding"details": nullin logs.- The
@civility/honoroute wrappers (§14.6.1) do not threadmessageKeyyet — no route sends one today. A route that needs it can call this builder withc.json()directly; the wrapper grows the parameter when a real consumer appears.
14.5.2 isErrorResponse guard #
function isErrorResponse(body: unknown): body is ErrorResponse
Used when parsing an unknown JSON body (e.g. from a binary endpoint where the
body is not normally deserialised on the happy path). Checks that body is a
non-null object with status === 'error', a string code, and a string
message.
14.6 Integration Points #
14.6.1 With the server (§13) #
@civility/hono does not wrap c.json() in every route. It provides internal
helpers in packages/hono/utils/response.ts that adapt the builders to a Hono
Context:
ok<T>(c, data, message = 'ok', status = 200): Response
err(c, code: ErrorCode, message, details?, status?): Response
err()defaults the HTTP status tohttpStatusFor(code), so routes rarely specify one and read left-to-right:(c) => err(c, 'auth.invalid_credentials', '...').- These wrappers are internal to
@civility/hono; external consumers building their own middleware importok/err/httpStatusFordirectly from@civility/errors. - The global
onErrorincreateManager()(§13) emitscode: 'internal.server_error'with a generic message so unhandled throws don't leak stack traces to clients. - Errors are surfaced to telemetry as OpenTelemetry span attributes by the
server's OTel middleware (§13) — no
@civility/errors-level hook is required.
14.6.2 With sync (§3) #
SyncApi is the sole producer of CivilityApiError on the client. Its flow:
fetch()the endpoint; attemptresponse.json()(on failure,body = null).- If
!response.ok:- if
isErrorResponse(body)→CivilityApiError.fromResponse(body, response.status); - otherwise construct one with
code: 'internal.unknown'andmessage: body?.message ?? 'HTTP <status>'.
- if
- On thrown
AbortError→sync.request_timeout(408). - On any other throw →
sync.network_error(0). - On success, return
body.data.
Synced catches these inside sync(), maps them to a SyncErrorPhase, and
dispatches a SyncErrorEvent. Those types are owned by §3 (Sync).
14.6.3 With app code #
App developers rarely import from @civility/errors directly:
CivilityApiErroris re-exported by@civility/cloud.SyncErrorContext/SyncErrorPhaseare re-exported by@civility/cloud.ok/errbuilders are server-side tooling, rarely needed on the client.- Apps embedding
@civility/honointo a larger Hono app may needErrorCodefor typing custom middleware; it is re-exported from both@civility/honoand@civility/cloud.
14.7 Exports #
Single entry point:
{ "name": "@civility/errors", "exports": { ".": "./mod.ts" } }
mod.ts re-exports:
- Values:
ErrorCodes,domainOf,httpStatusFor,CivilityApiError,ok,err,isErrorResponse. - Types:
ErrorCode,ErrorDomain,KnownErrorCode,CivilityApiErrorInit,SuccessResponse,ErrorResponse,ApiEnvelope.
The package is small enough that subpath exports would be pure overhead; a
future surface (e.g. ./telemetry) could be added without breaking the main
entry. docs.ts (§14.3.6) is intentionally outside the export graph — it is
build tooling, not API — so it does not change this calculus.