Reference

Errors

fx.fail helpers, built-in HTTP statuses, OKE codes, and subsystem errors — values vs thrown invariants.

OKE has two error families: failures are values a Flow returns ({ data: null, error: { code, data } }), while framework errors are thrown for invariant violations (permanent numeric code + cause + fix).

OKE1110  domain table not found — migrations have not been applied.
         → run `oke db migrate` against this environment.
         https://oke.omqkhafi.dev/e/1110

Codes are stable after the domain-range renumber — match them safely across upgrades (see the Unreleased Breaking Changes mapping if you still have a pre-renumber note).

The one rule

Switch on error.code (or a match named arm) for typed data. Use kind arms / explain for chrome when the code is unknown. Catch OKE#### only for thrown framework invariants.

Smallest Example

Return a typed failure

on(
  http.get({
    in: z.object({ id: z.string() }),
  }),
  flow({
    do: async ({ id }, fx) => {
      const [row] = await fx.store(db).select().from(notes).where(eq(notes.id, id));
      if (!row) return fx.fail.notFound({ id });
      return row;
    },
  }),
);

Handle it on the client

import { match } from "okengine/client/explain";

const result = await api.notes.get({ id });
match(result, {
  ok: (note) => render(note),
  NotFound: () => showMissing(),
  _: (e) => toast(e.message),
});

fx.fail

Same function as import { fail } from "okengine". Returns { data: null, error } — it does not throw. Built-in codes need no errors: bag. Domain codes (OutOfStock, FlightFull, Duplicate) still go on the exposure:

on(
  http.post({
    in: z.object({ sku: z.string() }),
    errors: { OutOfStock: z.object({ available: z.number() }) },
  }),
  flow({
    do: async ({ sku }, fx) => {
      const available = 0;
      if (available === 0) return fx.fail("OutOfStock", { available });
      return { sku };
    },
  }),
);

Optional { message } overrides the catalog: fx.fail("OutOfStock", data, { message }).

Helpers

CallCodeStatusPayload
fx.fail.notFound(data?)NotFound404id?, key?, …
fx.fail.unauthorized(data?)Unauthorized401reason?
fx.fail.forbidden(data?)Forbidden403gate?, reason?
fx.fail.conflict(data?)Conflict409constraint?, table?, column?, id?
fx.fail.foreignKey(data?)ForeignKey409constraint?, table?, column?
fx.fail.rateLimited(data?)RateLimited429retryAfterMs?
fx.fail.serviceUnavailable(data?)ServiceUnavailable503retryAfter?
fx.fail.database(data)DatabaseErrorby data.reasonreason, sqlstate?, constraint?, table?, column?
fx.fail.internal(data?)InternalError500{} — catalog message only

DatabaseError status: not_null / check / invalid / too_long / out_of_range → 422, retryable → 503, unknown / missing → 500.

Declare a built-in on errors: only to tighten the payload. Shorter keeps NotFound: z.object({ code: z.string() }) because { code } is not the built-in { id? }. Declared schema wins on the Manifest and the typed client.

The typed client always includes built-in codes. A declared key still wins.

HTTP status

A bare 404 with body Not Found means no route matched. fx.fail.notFound is a JSON envelope at 404. Clients distinguish by envelope, not status. Domain codes stay 400.

CodeStatusHelper
ValidationError422none — failed in, do never runs
IdempotencyKeyMissing400none — idempotency: "required" and no header
IdempotencyKeyInvalid400none — header is not 16–255 printable ASCII
IdempotencyKeyReused422none — same key, different payload
IdempotencyInProgress409none — Retry-After until the in-flight call finishes
Unauthorized401unauthorized · also a gate denial
Forbidden403forbidden · also a gate denial
NotFound404notFound
Conflict / ForeignKey409conflict / foreignKey
UnsupportedMediaType415none — QUERY, or a JSON-shaped body that is not application/json / +json
PayloadTooLarge413none — body exceeds maxRequestBodySize or the route maxBodySize
RateLimited / AuthRateLimited429rateLimited · AuthRateLimited has none
InvalidQuery400none — QUERY or JSON body that does not parse (malformed_body)
AuthFailed400none — credentials / policy, not “no session”
DatabaseErrorby reasondatabase
ServiceUnavailable503serviceUnavailable
InternalError500internal — never copies a thrown message
Domain (OutOfStock, FlightFull, Duplicate)400fx.fail("OutOfStock", data)

UnsupportedMediaType (415) is this rule, for a non-empty body. Let mt be the media type before ;:

  1. application/json or application/*+json is parsed. A parse failure is 400 InvalidQuery with reason malformed_body.
  2. A route with jsonContentType: "any" tries JSON and otherwise keeps the raw string.
  3. text/plain, form-urlencoded, multipart, or a missing type, when the trimmed body starts with { or [ and parses as JSON, is 415.
  4. Anything else is the raw string. curl -d needs -H 'content-type: application/json'.

OKE1074 means the durable run lost its lease. The step result is not written and compensation does not run. The caller sees a busy lease, not a new failure of the work.

OKE1076 means codeVersion was set and the stored stamp is a different app: value. Leave the old value pinned until sleeping runs drain, then change it. Unset codeVersion checks nothing. A stored stamp from 0.23.1 (no app: prefix) is restamped, not failed.

Client chrome

import { match, matchError, explain } from "okengine/client/explain". Do not switch on every code — a create can return store auto-map, gates, transport, and domain codes.

kindCodes
authUnauthorized, AuthFailed
permissionForbidden
missingNotFound; TransportError with HTTP 404
conflictConflict, ForeignKey
invalidValidationError, InvalidQuery, UnsupportedMediaType; DatabaseError 422 reasons
limitedRateLimited, AuthRateLimited
unavailableServiceUnavailable; DatabaseError retryable; other TransportError
failedInternalError, unknown DatabaseError, domain codes
match(result, {
  ok: (data) => show(data),
  FlightFull: (data) => offerWaitlist(data.seatsLeft),
  auth: () => goSignIn(),
  invalid: (e) => setForm(e.fields),
  _: (e) => toast(e.message),
});

Dispatch: ok → named code → kind → required _. explain(error).fields maps ValidationError issues to { email: "Required" }. Full loop: Calling.

TransportError always sets both error.message and error.data.message to the same string. Prefer error.message in UI code.

Store auto-map

fx.store constraint and connection failures become typed fail values (same family as ValidationError). Public data is names only — never message / detail / hint. get returning null is not auto-NotFound — return fx.fail.notFound yourself.

SQL auto-map

SignalResult
Postgres 23505 / 23P01 · SQLite UNIQUE / PRIMARY KEYConflict 409
Postgres 23503 / 23001 · SQLite FOREIGN KEYForeignKey 409
Postgres 23502 / 23514 · SQLite NOT NULL / CHECKDatabaseError not_null / check 422
Postgres 22P02 / 22007 / 22023 / 42804DatabaseError invalid 422
Postgres 22001DatabaseError too_long 422
Postgres 22003 / 22008DatabaseError out_of_range 422
Postgres 40001 / 40P01 / 55P03 · SQLite BUSYleft thrown so flow.retry can run; after exhaust → ServiceUnavailable 503
08xxx / 53xxx / 57P0x / 57014 / 25P03 / connection / pausedServiceUnavailable 503
42P01 / 42703 with domainDdl: "off"OKE1110 (unchanged)
other SQLSTATEDatabaseError unknown 500

KV auto-map

Redis-wire store.kv only (not Gate / Signal clients). Memory KV does not throw these.

SignalResult
Connection / CLUSTERDOWN / READONLY / OOM / MISCONFServiceUnavailable 503
BUSY / TRYAGAIN / LOADINGleft thrown so flow.retry can run; after exhaust → ServiceUnavailable 503
WRONGTYPE / NOSCRIPTunmapped — InternalError 500

Files auto-map

fs and s3 (fx.store files handle). Missing objects stay null.

SignalResult
AccessDenied / EACCES / EPERM / HTTP 403Forbidden 403
fs key starts with / or contains ..Forbidden 403 (reason: invalid_key)
NoSuchBucket / ENOSPC / connectionServiceUnavailable 503
SlowDown / EBUSY / HTTP 429left thrown so flow.retry can run; after exhaust → ServiceUnavailable 503
NoSuchKey (thrown)unmapped — InternalError 500

Localized messages

Typed failures and OKE codes ship English and Arabic ICU catalogs. Locale comes from Accept-Language (matched to i18n.locales); fallback is i18n.default.

SurfaceKeysHow it appears
fx.fail / failerrors.{code} · errors.{code}.{reason}Optional error.message on the envelope
Thrown OkeErroroke.{code}.cause · oke.{code}.fixCause + fix lines in the thrown message

Override via defineLocale. Pass fail(code, data, { message }) for a custom string. Custom app codes stay message-less until registered. Full catalogs: i18n.

OKE numeric codes

CodeNameCauseFix
1001undeclared readFlow reads a resource not in effects.readsAdd it to the flow's effects.reads
1002undeclared writeFlow writes a resource not in effects.writesAdd it to the flow's effects.writes
1003undeclared emitFlow emits a signal not in effects.emitsAdd it to the flow's effects.emits
1004undeclared sendFlow sends a template not in effects.sendsAdd it to the flow's effects.sends
1005undeclared askFlow asks a prompt not in effects.asksAdd it to the flow's effects.asks
1006undeclared secretFlow reads a secret not in effects.secretsAdd it to the flow's effects.secrets
1007undeclared callFlow calls a flow not in effects.callsAdd it to the flow's effects.calls
1008undeclared fetchFlow fetches a host not in effects.fetchesAdd the hostname to the flow's effects.fetches
1009undeclared embedFlow embeds with a model not in effects.embedsAdd it to the flow's effects.embeds
1020no effects declaredFlow has no effects and no Manifest to infer fromRun oke build / oke dev, or declare effects
1030adopt barrel staleA src/flows/<unit> folder was not adoptedRun oke dev or oke build to regenerate src/flows/index.ts
1040HTTP path unresolvedPathless http.get() never received a file-tree stampImport @/flows, or pass http.get("/…")
1041HTTP route clashTwo HTTP flows share the same method + pathGive each flow a unique method + path
1045HTTP flow unnamedAdopted HTTP flow still has no unit.exportExport from flows/<unit>/ or pass a named flow
1050live exposure dupSame signal, gates, and match on two GET routesChange the gate or path-param filter
1060MCP tool duplicateTwo MCP tool bindings share the same tool nameGive each MCP tool exposure a unique name
1070flow name duplicateTwo Flows share the same Manifest / fx.call nameGive at least one an explicit flow("…") or tree export
1071once-signal multi-flowTwo different Flows bound to the same signal.onceUse signal.broadcast, or bind only one Flow
1072flow unnamedSignal / Clock consumer still has no unit.exportExport from flows/<unit>/ or pass a named flow
1110schema missingDomain table absent in prod — no auto-DDLRun oke db migrate against this environment
1510vault secret missingContract has no value in any resolution layeroke vault set <name>, .env.local, or a dev: fallback
1210live resume gapLast-Event-ID is not on the retained tapeReconnect without the cursor; remaining tape replays
1240orphan emitEmit with zero subscribers and optional falseAdd on(signal, …) or declare optional: true
1250signal schemaEmit payload failed the signal's schemaPass a payload that matches schema, or remove it
1605channel schemaSend payload failed the template's schemaFix template data payload or the template schema
1810tenant requiredTenant-scoped op with no fx.tenant.idswitchTenant, signed tid, or tenant header
1820tenant not memberClient-supplied tenant id is not a membershipPick from listTenants or add the user as a member
1830tenant unknown scopeTenant role used an invented or console:* scopeUse a declared application scope

Effects are usually inferred

The 1001–1007 · 1008 · 1009 family exists for flows that declare effects explicitly. Most apps never write an effects block — inference covers them — so seeing one of these means an explicit declaration drifted from the code.

Gate denials (typed failures)

Returned before do — not thrown. Same codes as fx.fail.unauthorized / .forbidden / .rateLimited:

CodeWhenPayload
UnauthorizedPolicy denied, request not authenticated—
ForbiddenPolicy denied, authenticated but not allowedgate, reason (tenant_required · not_member · unknown_scope · session_only · …)
RateLimitedRate gate budget exhaustedretryAfterMs

Subsystem errors

Thrown by specific subsystems — each names its own cause:

ErrorThrown whenWhat to do
VaultBootErrorA vault contract has no value in any resolution layerTTY OKE1510 — set each listed name
VaultError (UNSUPPORTED)Managed provider unknownUse an official id, built-in vault, or env
VaultSealedConsole rotate-master while this process holds no master keyExport OKE_VAULT_MASTER_KEY or run oke vault unseal
VaultRotateBusyMaster-rotation lease held or a batch is already in flightWait and continue, or resume with oke vault rotate-master --new-key
VaultUnsupportedConsole vault action on a non-builtin backend or missing SQLUse drivers.vault = "vault" and set DATABASE_URL
AiPiiBuildErrorBuild: a flow sends PII fields to a third-party modelDrop the fields or add allowPii: true — fields named
AiSchemaValidationErrorA model response failed the prompt's out schemaFix the prompt or the schema — response didn't conform
ScheduleNotOverridableErrorConsole tried to edit a clock declared without overridable: trueDeclare it overridable and redeploy
ClockResourceNotFoundErrorConsole action targeted an unknown clock nameCheck the name against your clock() declarations
DryRunWriteIsolationErrorA write attempted inside a dry runDry runs never write — use a real run
ManifestValidationErrorThe compiled Manifest failed schema validationRe-run the build; the error names the offending entry
CrossPlaneErrorA user-plane token was used on the operator plane (or vice versa)Use the correct principal for the plane
AttenuationErrorA token was used beyond its attenuated scopeRe-issue with the needed scope
SessionErrorSession token invalid, expired, or malformedRe-authenticate
OperatorErrorOperator-plane operation failed its checksError message names the failed check
AccessGrantErrorConsole access grant rejectedRe-request access with a valid grant
UnsupportedPathErrorA route path shape the router can't compileSimplify the path pattern

Troubleshooting

Learn more

  • fx — fx.fail helpers on the door
  • i18n — catalogs, fx.t, locale matching
  • Flow — envelope and domain errors:
  • HTTP — response envelopes
  • Calling — match / explain on the client
  • Gate — where the three denials come from
  • CLI — oke db migrate and friends

Next

On this page