Error handling
Schema-tagged error variants, runtime errors vs business errors, client narrowing, retry semantics.
Voltro distinguishes business errors (typed, declared in the schema, expected) from runtime errors (unexpected exceptions, transport failures, framework bugs). Each surface has clear semantics.
Live — demo.greet throws a typed NameTooLong for a name over 20 chars; the
client narrows on _tag and reads the typed fields:
const greet = useAction('app', 'demo.greet')
try { await greet.run({ name }) }
catch (e) { if (e._tag === 'NameTooLong') { /* typed: e.max, e.actual */ } }
Business errors
Declare your own with Schema.TaggedError — the class-extension form:
import { Schema } from 'effect'
class InsufficientFunds extends Schema.TaggedError<InsufficientFunds>()('InsufficientFunds', {
required: Schema.Number,
available: Schema.Number,
}) {}
class TitleTooLong extends Schema.TaggedError<TitleTooLong>()('TitleTooLong', {
maxLength: Schema.Number,
}) {}Wire them into a mutation / action / query via the error field:
export const transfer = defineMutation({
name: 'wallet.transfer',
guards: [{ scope: 'wallet:transfer' }],
input: Schema.Struct({ to: Schema.String, amount: Schema.Number }),
output: Schema.Struct({ txId: Schema.String }),
error: Schema.Union(InsufficientFunds, TitleTooLong),
})
export default async (input, ctx) => {
const wallet = await ctx.store.select('wallets').where('id', ctx.request.subject.id).one()
if (wallet.balance < input.amount) {
throw new InsufficientFunds({ required: input.amount, available: wallet.balance })
}
// …
}Client narrows on _tag:
const transfer = useMutation('app', 'wallet.transfer')
const result = await transfer.mutate({ to: 'usr-42', amount: 100 }).catch((e) => e)
if (result._tag === 'InsufficientFunds') {
// result.required, result.available are typed
toast.error(`Need ${result.required}, have ${result.available}`)
} else if (result._tag === 'TitleTooLong') {
toast.error(`Too long — max ${result.maxLength}`)
} else if ('txId' in result) {
toast.success(`Transfer ${result.txId} complete`)
}One error shape on every client surface
An rpc failure reaches your code as the typed error itself — the error the descriptor declares, with its _tag and fields. Not a wrapper around it: not an Effect Cause ({ _tag: 'Fail', error }), not a FiberFailure, not an Error with the typed value under a property. Any of those would make every _tag branch fall through to the generic one.
It is the same value on every surface, and it is the value the api's error bus carries in useOnRpcError's event.error for the same failure — one _tag switch serves all of them:
| Surface | Where the failure appears |
|---|---|
useSubscription (also with fallback / initialSnapshot) |
error — the cold-start failed: true state |
useRecord · useDataTable · useWindowedSubscription |
error |
useMutation |
mutate(input) rejects · error · onError(err) |
useAction |
run(input) rejects · error · onError(err) |
useWorkflow |
start · cancel · resume · signal · update reject |
useWorkflowSignal / useWorkflowUpdate |
signal · update reject |
useUpload |
upload · uploadMany reject |
A loader's ctx.query |
rejects — on the server and in the browser, for a refused query and a failed call alike |
ctx.apis.<name> (server-to-server) |
call rejects · subscribe's onError(err) |
useOnRpcError / useOnRawRpcError |
event.error |
What the value is, by cause:
- A declared failure (a typed error in
error:, or one the framework merges in, such asScopeErrororUnauthenticated): the typed error. Over the wire it is decoded from JSON, so match on the tag (errorTag(err)orerr._tag), not withinstanceof. - A transport failure (the socket dropped, the api is unreachable): an
RpcClientError—_tag: 'RpcClientError', withreasonandmessage. On the error bus itskindis'transport'. A server-to-servercallreports "no answer" asApiUnavailableinstead, and a loader's server-sidequery— a one-shot HTTP call, not the socket — as anErrornaming the api origin it could not reach and the setting that points at it. - A defect (an undeclared
throwon the server, a bug): the value the handler died with, usually a plainErrorwith no_tag— so it falls to your generic branch, which is the intended split. Check_tagfor the outcomes you declared; treat everything else as unexpected.
To show it, use errorMessage(err), not String(err). A declared error arrives as the plain object decoded from the wire, and String() of a plain object is [object Object]. errorMessage returns its message, else its _tag, else String(err) — for a transport failure and a defect alike. errorTag and errorMessage are exported by @voltro/client and @voltro/protocol:
import { errorMessage, errorTag, useSubscription } from '@voltro/client'
const { error, failed } = useSubscription(listTeams, {})
if (failed) return errorTag(error) === 'AccessDeniedError'
? <p>You are not a member of this team.</p>
: <p>Could not load: {errorMessage(error)}</p>The same holds in an error.tsx boundary: a loader that does not catch a refusal throws the declared error, so the boundary's error is that object — render errorMessage(error). An error reporter gets it as an Error named by its _tag (the Sentry web integration does this for you; reportableError(err) from @voltro/protocol is the helper).
Passing onError (or notify.error) to a write resolves it with undefined and hands that same typed value to your handler. See Mutations.
Tagged errors:
- Are wire-safe — they serialise as JSON (the rpc transport is
RpcSerialization.layerJson) and restore on the client with the correct_tag+ payload. - Narrow correctly in TypeScript via the
_tagdiscriminant. - Carry typed payload fields.
- Don't fire alerts / unhandled-promise-rejection signals — they're expected business outcomes.
Runtime errors
Unexpected throws — TypeError, RangeError, framework bugs, third-party SDK failures — don't match the descriptor's error union, so they surface as defects rather than typed failures:
- The throw is logged (via
@voltro/loggerto your configured sink). - The client sees a generic failure (no typed payload — runtime errors might leak sensitive context).
- The trace records the throw + trace ID for cross-referencing;
voltro logs --trace <id>returns the whole causal chain. - The trace is searchable in OpenTelemetry.
To distinguish "we know about this" from "this surprised us":
| Throw | Treatment |
|---|---|
throw new InsufficientFunds({ … }) (declared tagged error in error:) |
Marshalled to the client typed, no log-volume increase |
throw new Error('oops') |
Surfaces as a defect — full log + trace, generic failure to client |
| Unexpected exception from a library | Same — caught, logged, generic failure |
A tagged error that is not in the procedure's wire union is not delivered as itself either. A mutation or action answers InternalError whose message starts with the tag (NotFoundError: …), and the server logs once per procedure and tag that the tag is undeclared and how to declare it; a query delivers the tag in-band, but the client's typed union does not contain it. An executor wrapped in defineExecutor turns that into a compile error at the handler.
What the framework merges into your error: union
You do not declare the errors the framework itself can raise for a procedure — they are unioned into the wire contract for you, and only when the procedure can actually produce them:
| Merged | Into | When |
|---|---|---|
Unauthenticated |
query · mutation · action · stream · event · workflow start | always. The auth middleware sits on the whole rpc group, so a rejected credential (an expired token, a revoked key) refuses an openAccess: procedure exactly as it refuses a guarded one — and a handler may refuse on its own with assertAuthenticated, whatever its descriptor declares. A guard can also refuse for this reason: the caller presented a credential that was REJECTED and so arrived anonymous. Without it in the union, an expired session reads as a permissions problem — or, worse, as an InternalError wearing the tag |
ScopeError |
query · mutation · action · stream · workflow start | always. A declared guards: entry refuses with it before the executor runs, and a handler may refuse with requireScope whether or not the descriptor carries a guard |
ScopeError |
event | the event declares a real guards: entry. NOT for openAccess: — an event has no handler that could refuse on its own, so an open event advertising a denial it cannot produce is what makes an error union stop meaning anything |
BusinessRuleViolation |
mutation | always. A cross-table rule() on any table the mutation writes can fail it, and the descriptor cannot know which tables carry rules |
ApprovalRequired · ApprovalExpired · ApprovalUnavailable |
mutation · action | the procedure declares requiresApproval: |
NoSuchResource |
query · mutation · action · stream · event · workflow start | a guard names a resource — a relationship guard, or a scope guard with a resource extractor. Raised when the app's tuple source or resolver answers 'missing' for a signed-in caller; see Authorization |
So a guarded mutation does not need ScopeError in its own error:, and a
handler that gates itself does not need Unauthenticated in it either. If you
declared them anyway, that is harmless — the union is the same either way.
A refusal on a subscription travels in-band — a { _tag: 'error' } event on
that one stream, so a sibling subscription on the shared socket is not stalled
— and the same typed value reaches the api's error bus, where
wireAuthRefresh and useOnRpcError see it exactly as they see a refused
mutation.
Framework-shipped error variants
@voltro/protocol exports the framework's own tagged errors. The rest of your typed errors are ones you declare yourself (above) or ones a plugin contributes.
Import them from @voltro/protocol, not from @voltro/runtime — even the store errors the runtime raises. A descriptor that declares one in error: is loaded value-level by the web client (the RpcClient needs every procedure's Schema), and @voltro/runtime is server-only, so a descriptor importing from it is refused at boot by the browser-safety guard. @voltro/runtime re-exports them for server code, which never sees the difference.
| Variant | From | When |
|---|---|---|
ScopeError |
@voltro/protocol |
requireScope(subject, scope) failed — { required, message }. |
Unauthenticated |
@voltro/protocol |
The resolved Subject is anonymous but a signed-in caller was required — optional { reason }. |
TenantScopeViolation |
@voltro/protocol |
A tenant-scoped EffectStore write had no authenticated subject. |
NoSuchResource |
@voltro/protocol |
A resource guard refused because the app's tuple source or resolver answered 'missing' — { resourceType, resourceId, message } (resourceType is null for a scope guard). Never raised for an anonymous caller, and never inferred from an empty tuple set. |
TenantRowNotFound |
@voltro/protocol |
A keyed-by-id write (store.update(t, id, …), delete, hardDelete, patchJson) on a tenant() table found no such row in the caller's tenant. Raised identically whether the row is missing or belongs to another tenant — the distinction would be a cross-tenant existence oracle. |
ServerOnlyColumnWrite |
@voltro/protocol |
A crud.create / crud.update input tried to set a .serverOnly() column — { table, columns }. |
StoreOperationFailed |
@voltro/protocol |
The underlying store operation failed — { operation, table, cause }. cause is a bounded description: a sentence the framework authored travels whole; a driver failure is reduced to its class and code. See below. |
TableValidationFailed |
@voltro/protocol |
A table().validate(Schema) row check rejected the write. |
ConstraintViolation |
@voltro/protocol |
The database refused the write on a foreign key / unique / NOT NULL / CHECK — { kind, table, operation, constraint?, column? }. See below. |
CacheError |
@voltro/cache |
A cache backend op failed — { operation, key, cause }. |
RateLimited |
@voltro/plugin-ratelimit |
The limiter rejected the call — { limit, retryAfterMs, resetAtMs }. |
TenantMismatch |
@voltro/plugin-multitenancy |
assertOwnTenant(input.tenantId, subject) rejected a cross-tenant write. |
Each plugin that ships an error (RateLimited, EntitlementExceeded, StorageError, MailError, …) merges it into every procedure's wire-error union, so the client decodes it typed without you adding it to each error:. That includes an app's OWN plugin: an error registered through a local plugin's errorSchemas is declared app-wide, for queries, mutations, actions and streams alike, on both voltro dev and voltro serve. To surface a store error to the client, add it to the descriptor's error: union yourself (e.g. error: Schema.Union(TenantScopeViolation, StoreOperationFailed, MyDomainError)).
All carry _tag + typed payloads, all narrow correctly on the client.
EffectStore mirrors the Promise store on this typed channel: query, one,
maybeOne, first, insert, insertMany, patchJson, update,
updateMany, delete, deleteMany, upsert, insertIgnore, hardDelete,
and transactional. A transaction receives another EffectStoreOps; a typed
failure or defect from its inner Effect rolls the transaction back and keeps its
original Cause. Store/commit failures become StoreError.
one fails with NoRowFound on its own channel rather than as a store failure,
so it stays catchable:
const note = yield* store.one({ table: 'notes', predicate: eq('id', input.id) })There is no onMissing on the Effect surface — Effect.catchTag('NoRowFound', …) says the same thing and keeps the failure channel exact. NoRowFound comes
from @voltro/protocol, so a descriptor can declare it in its error: union.
The fluent BUILDER (ctx.store.select(...).unscoped() and its chain) remains
the Promise surface — pass its .descriptor to store.query when you need it
on the Effect channel. Do not replace an intentionally unscoped lookup merely to
use EffectStore; Doctor only recommends the Effect surface for methods it
actually exposes.
When the database refuses the write
An integrity rule your schema declares — a reference(), a .unique(), a non-nullable column, a .check() — is enforced by the database, not by the handler. When it fires you get a ConstraintViolation:
{ _tag: 'ConstraintViolation',
kind: 'foreignKey', table: 'tasks', operation: 'insert',
constraint: 'tasks_laneId_fkey' }kind is the field to branch on, and it is the one field every dialect can always fill:
kind |
Means | The caller's fix |
|---|---|---|
foreignKey |
the row you referenced does not exist | point at a real row |
foreignKeyInUse |
this row may not go — others still reference it | delete the children first, or don't delete |
unique |
a row with this value already exists | pick another value |
notNull |
the column requires a value | send one |
check |
the row does not satisfy a declared .check() |
fix the value |
constraint and column are filled where the dialect names them. sqlite reports a foreign-key failure as the bare sentence FOREIGN KEY constraint failed — no name, no column — so constraint is absent there and the direction is inferred from the operation.
It carries names, never the driver's sentence, and that is deliberate. The message the database produces contains row DATA on most engines: postgres attaches Failing row contains (…) — the complete row, every column, .sensitive() ones included — to a not-null and a check violation; mysql and mssql echo the duplicate value on a unique violation. A constraint name is schema, the same class of fact TableValidationFailed.table already puts on the wire. A row is data, and the caller who provoked the error is not automatically entitled to it. The full driver text is in the server log, with the trace id.
Declare it in error: to pattern-match it:
error: Schema.Union(ConstraintViolation, MyDomainError),If you do not, it still reaches the client — collapsed to InternalError like any undeclared error, but carrying its own sentence (ConstraintViolation: foreign key tasks_laneId_fkey on tasks: the referenced row does not exist) rather than the opaque Failed to execute statement a raw SqlError produces.
StoreOperationFailed does not stand in for it. A typed refusal reaches you
as itself — ConstraintViolation, TableValidationFailed, ServerOnlyColumnWrite
— and is never re-wrapped. StoreOperationFailed is the catch-all for what is
left: a broken connection, a driver fault, a refusal the framework itself raised
(an eager load on a table with no relations registered, an unknown relation
name), anything the framework could not classify.
Its cause is a bounded description, and its message reads as one sentence —
query on 'schedules' failed: cannot eager-load on 'schedules': no relations registered. Did you forget to declare \relations(schedules, ...)` or import
the file that does?— in a test reporter, inCause.pretty, and in the undeclared-error envelope alike. What cause` carries depends on who wrote the
text:
- A sentence the framework authored travels whole. It names code and schema — an operation, a table, a column, a relation — and nothing else, so the diagnosis reaches whoever reads the failure instead of the bare class name of the error that carried it.
- A driver failure is reduced to its class and its code —
SqlError (57P01),Error (ECONNREFUSED). The driver's sentence never travels, for the same reasonConstraintViolationrefuses it: on several dialects it contains row data, and a connection error's contains the socket address. The full driver text is in the server log, with the trace id.
So if a descriptor declares only
error: Schema.Union(StoreOperationFailed),in order to catch constraint failures, it no longer does. Declare the variant you want, or take the whole set:
error: Schema.Union(StoreError),tsc cannot warn you here — the store's failure channel has always been typed
StoreError, which includes every variant. Only the value you receive changed.
When the FRAMEWORK refuses the write
A few refusals are ours rather than the database's. The MySQL-family upsert has
one: ON DUPLICATE KEY UPDATE fires on whichever unique key the incoming row
violates, which may not be the one your conflictColumns named, so the store
checks afterwards and rolls back when the statement reached a row those columns
could not have selected. The database was perfectly happy — we are the ones
saying no.
These arrive as ConstraintViolation too, on the same failure channel and with
the same kind, so nothing downstream needs a second branch. They were plain
throws until 0.58.0, which made them defects: the client received a Defect
wrapping a stringified InternalError, with no tag to match on, for a condition
an app can genuinely branch on.
They carry one extra field:
{ _tag: 'ConstraintViolation',
kind: 'unique', table: 'projectHours', operation: 'upsert',
detail: 'MysqlStore.upsert: the row written to …' }detail is a sentence the framework authored, and it replaces the generated one
in message. It is populated only for these refusals — never from a driver
message, and never with a row value. That is the same rule the generated sentence
follows: on several dialects the driver's own text contains row data, so it is
not forwarded. A sentence we wrote carries exactly what we put in it.
Loader errors
Loaders run in the web app — they receive { params, query, headers, signal }, NOT a server ctx with .store. A loader reaches the backend through query(...) (POST /rpc on the server, the page's WebSocket in the browser). It short-circuits with the branded control-flow signals NotFoundError / RedirectError:
import { notFound } from '@voltro/web'
export const loader = async ({ params, query }) => {
// `query` is there on the server and in the browser; undefined only in an app with no api.
const note = query ? await query('notes.get', { id: params.id }) : undefined
if (!note) throw notFound(`note ${params.id}`) // → scoped not-found.tsx / 404
return note
}When the rpc refuses, query rejects with the declared error itself — the same value a hook's error would hold — whether the query was refused (a guard, an in-band error) or a call failed on its error channel. Branch on its tag; anything you do not handle propagates like any other throw:
import { errorTag } from '@voltro/protocol'
export const loader = async ({ params, query }) => {
try {
return await query('notes.get', { id: params.id })
} catch (err) {
if (errorTag(err) === 'ScopeError') return null // render the page without it
throw err
}
}A NotFoundError answers 404 with the nearest not-found.tsx, inside the layouts above the loader that threw — it is NOT routed to the error.tsx boundary. A plain throw new Error(...) DOES hit error.tsx on a client navigation (a server render answers 500; see Errors from loaders):
export default function ErrorPage({ error, reset }: { error: Error; reset: () => void }) {
return <GenericError error={error} reset={reset} />
}See Loaders & meta for NotFoundError / RedirectError and the ctx.query SSR path.
Retry semantics
| Surface | Auto-retry? | Notes |
|---|---|---|
useSubscription |
✓ on disconnect | The api connection auto-reconnects with exponential backoff (500ms × 2^(attempt-1), capped at 5s) and re-subscribes; the server replays the current snapshot. Reconnect attempts are not capped — it keeps trying until the connection is restored or the component unmounts. |
useMutation |
✗ | Mutations might be non-idempotent. Retry only when the operation is safe to repeat. |
useAction |
✗ | Same. |
useAgentStream / useAgent |
✗ | Streaming is hard to resume. Use a workflow for durable agent runs. |
| Workflow steps | ✓ | Configurable per-workflow + per-step. |
For mutations that are safe to repeat, wrap mutate in your own retry:
const result = await retry(
() => create.mutate(input),
{ attempts: 3, backoff: 'expo' },
)For operations that must be durable or exactly-once across disconnects, queue the work through a workflow and use database uniqueness constraints around the business key.
Validation errors
Each rpc decodes its input against the declared input schema before the executor runs. A payload that fails the schema is rejected by @effect/rpc as a decode failure — the executor never runs. To surface field-level messages to a form UI, declare your own validation error and decode the input yourself in the handler:
import { Schema } from 'effect'
class ValidationFailed extends Schema.TaggedError<ValidationFailed>()('ValidationFailed', {
errors: Schema.Array(Schema.Struct({ path: Schema.String, message: Schema.String })),
}) {}You can attach custom messages to the field constraints with Schema.message:
Schema.String.pipe(
Schema.minLength(1, { message: () => 'Title is required' }),
Schema.maxLength(200, { message: () => 'Title is too long (max 200 chars)' }),
)Schema-level row validation on a table (table().validate(Schema)) throws the runtime's TableValidationFailed — declare it in the mutation's error: to surface it typed.
Network errors
A WebSocket disconnect interrupts in-flight unary calls — the awaited mutate / run rejects. The framework reconnects query subscriptions automatically; for mutations and actions, you decide whether retrying is safe:
try {
await create.mutate(input)
} catch (e) {
// Connection dropped mid-call. Wait for the api to reconnect, then retry
// ONLY if the operation is idempotent.
await waitForReconnect()
await create.mutate(input)
}Anti-patterns
- Throwing a DECLARED error inside
Effect.promise/Effect.sync. Those combinators turn every throw into a defect, not a failure — so an error your descriptor promises the caller in itserror:union is discarded on the way out, and the client shows a generic message instead of yours. The shape is invisible at the call site: it reads exactly like the working form.
// Wrong — the throw becomes a DEFECT, and the client sees a generic failure.
yield* Effect.promise(() => ctx.store.transactional(async (tx) => {
if (ticket.status !== 'revealed') throw new ValidationError({ field: 'status', message: '…' })
}))
// Right — the transaction returns an Effect, and the failure stays a failure.
yield* ctx.store.transactional((tx) => Effect.gen(function* () {
if (ticket.status !== 'revealed') {
yield* Effect.fail(new ValidationError({ field: 'status', message: '…' }))
}
})) Effect.tryPromise({ try, catch }) is the other way round — its catch is precisely the mapping from a throw onto the failure channel, so a throw is safe there. voltro doctor flags the lossy form as promise-swallows-typed-error.
- Swallowing every error and showing "Something went wrong". You're hiding genuine bugs. Let the dashboard's error pane +
voltro traces --errorssurface them; only catch the specific tagged variants you've declared. - Throwing strings.
throw 'oh no'→ surfaces as a defect, no useful payload. UseErrorsubclasses orSchema.TaggedErrorvariants. if (error instanceof InsufficientFunds)on the client. The wire-deserialised value isn't structurally identical to the server's class. Always check_tag.- The curried
Schema.TaggedError('Name')({...})form. That doesn't type-check — use the class-extension formclass X extends Schema.TaggedError<X>()('X', {...}).