Connected apps with 3rd-party data hosts jsr.io/@civility
civility docs spec features 14_errors.md
14 kB · 336 lines
Markdown
at main

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 #

  1. 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.
  2. Structured errors on the client. CivilityApiError (§14.4) carries a stable code so apps branch on meaning, not on message.includes('...').
  3. Codes are exhaustive but extensible. ErrorCodes lists the canonical set with default HTTP statuses. The public ErrorCode type unions the known literals with ${ErrorDomain}.${string}, so package-specific codes type-check without a registry update.
  4. HTTP status is derivable. httpStatusFor(code) returns the canonical status for a known code, or 500 for unknown codes. Callers may override (e.g. a 201 on create) but rarely need to.
  5. details is unknown. The envelope carries an optional details field whose shape is domain-specific. Consumers narrow it by branching on code first.
  6. One class, not an error hierarchy. Rather than AuthError extends CivilityApiError, QuotaError extends CivilityApiError, etc., there is a single class with a domain getter. Subclasses would force every package-of-use to depend on @civility/errors just to do instanceof, 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_error uses httpStatus: 0 — a client-only code emitted before any response is received. 0 signals "no HTTP status" to consumers.
  • sync.request_timeout is 408 (client-side abort), not 504 (upstream gateway timeout).
  • blob.url_unavailable is 500: the server could not produce a signed/CDN URL, which is a server-side configuration failure.
  • sharing.not_supported is 501 (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 #

  1. Add the literal to the KnownErrorCode union in codes.ts.
  2. Add the entry to ErrorCodes with its default HTTP status.
  3. Add a one-line description to ErrorCodeDescriptions in docs.ts (TS rejects a missing key) and run deno task docs to regenerate the README table (§14.3.6).
  4. 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 docs rewrites the README; deno task docs:check verifies it.
  • A test (__tests__/docs.test.ts) fails the suite whenever the README drifts from codes.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.ts is deliberately not exported from mod.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
}
  • name is set to 'CivilityApiError'.
  • cause is forwarded to Error's standard cause option (only when defined). @civility/cloud uses this to attach the underlying TypeError on a fetch() failure, or the original AbortError on 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 includes message, defaulting to 'ok' — keeping it non-optional simplifies the consumer's type narrowing.
  • err() sets details and messageKey only when they are defined, avoiding "details": null in logs.
  • The @civility/hono route wrappers (§14.6.1) do not thread messageKey yet — no route sends one today. A route that needs it can call this builder with c.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 to httpStatusFor(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 import ok / err / httpStatusFor directly from @civility/errors.
  • The global onError in createManager() (§13) emits code: '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:

  1. fetch() the endpoint; attempt response.json() (on failure, body = null).
  2. If !response.ok:
    • if isErrorResponse(body) → CivilityApiError.fromResponse(body, response.status);
    • otherwise construct one with code: 'internal.unknown' and message: body?.message ?? 'HTTP <status>'.
  3. On thrown AbortError → sync.request_timeout (408).
  4. On any other throw → sync.network_error (0).
  5. 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:

  • CivilityApiError is re-exported by @civility/cloud.
  • SyncErrorContext / SyncErrorPhase are re-exported by @civility/cloud.
  • ok / err builders are server-side tooling, rarely needed on the client.
  • Apps embedding @civility/hono into a larger Hono app may need ErrorCode for typing custom middleware; it is re-exported from both @civility/hono and @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.