Results and errors
Every call returns a Result with a typed, serializable DbError.
Repository methods never throw for database errors. They return an
AsyncResult, which you can await for a Result or unwrap:
const result = await db.customers.get(id);
if (!result.ok) {
if (result.error.kind === "not_found") return notFound();
throw result.error;
}
result.data.name;
// Or throw a DbException on error:
const customer = await db.customers.get(id).orThrow();
// Or chain:
const name = await db.customers
.get(id)
.map((row) => row.name)
.unwrapOr("Unknown");A DbException has the DbError as error and cause, and its own
kind, status, code, details, hint and table fields; see
Throwing your own errors.
AsyncResult has orThrow, unwrapOr, map, mapError and andThen.
mapError here rewrites the DbError inside one result; betterSupabase.mapError()
(below) changes what .orThrow() throws.
Error kinds
DbError is plain data, safe to return from server actions and RPC handlers.
| kind | status | From |
|---|---|---|
not_found | 404 | get, update, delete with no row, PGRST116, P0002 (no_data_found) |
unauthorized | 401 | Missing or expired JWT |
forbidden | 403 | 42501, RLS WITH CHECK failures; 25006, a write in a read-only transaction (with a hint); guards with aal set required (MFA); an authorizer refusal sets permission, and approval with code: "APPROVAL_REQUIRED"; a refusal that names the missing keys sets permissions |
conflict | 409 | 23505 unique violation, with constraint and columns; hint STALE_WRITE when an update's expectedVersion no longer matches (see Stale writes); SQLSTATE PT409 from a block function in a state conflict, with its hint (see Conflicts from functions) |
foreign_key | 409 | 23503 |
check | 422 | 23514, with constraint; a jsonb-schemas check is validation instead |
not_null | 422 | 23502, with column |
exclusion | 409 | 23P01 |
invalid_input | 400 | 22* data exceptions |
invalid_value | 500 | A stored value the app type can't hold, such as infinity in a Temporal timestamp, with column |
raised | 400 | RAISE EXCEPTION (P0001); hint carries your app code |
timeout | 504 | 57014 statement timeout, or a call past its timeout option |
serialization | 409 | 40001, safe to retry |
network | 503 | Fetch failures, 08*, and @supabase/server pool errors (POSTGRES_POOL_BUSY, POSTGRES_CONNECT_PAUSED); retryAfter is the seconds to wait, when known |
aborted | 499 | The AbortSignal fired |
invalid_request | 400 | A query the backend cannot express |
validation | 422 | Standard Schema issues from the validation extension, or the jsonb-schemas errors |
multiple_rows | 409 | A single-row call matched several rows |
stale | 412 | update(..., { expect }) found a newer row |
max_affected | 400 | A write matched more rows than its maxAffected, PGRST124; maxAffected is the limit |
rate_limited | 429 | Over a write rate limit; retryAfter is the seconds to wait |
quota_exceeded | 429 | A usage quota is used up; meter, limit and retryAfter (seconds until the period resets) |
truncated | 413 | An unbounded list was cut at maxRows and another row exists; table and maxRows. Add limit or use page() |
unsupported | 501 | The executor can't run the operation, such as an include on SQLite |
unexpected | 500 | Anything else |
The status field feeds the RFC 9457 problem details
mapping in the server adapters.
Stale writes
A block's update takes an expectedVersion: the updatedAt of the row as the caller read it. When the row changed since, the write is refused with a conflict error whose hint is STALE_WRITE (status 409), and nothing is written. Problem Details answers it with the type https://bettersupabase.com/problems/stale-write, so a client can refetch the row and offer the user the choice. isStaleWrite(error) from better-supabase tells it from a unique violation, which is also a conflict.
const task = await db.tasks.get(taskId).orThrow();
const saved = await db.tasks.update({
changes: [
{ taskId, field: "dueAt", value: friday, expectedVersion: task.updatedAt },
],
strict: true,
});
if (!saved.ok && isStaleWrite(saved.error)) {
// Reload the task and ask the user.
}The entities that take expectedVersion declare expectedVersion: true in their manifest entities. A change without one is last writer wins, as before.
Conflicts from functions
A block function that refuses a change because of the record's state, such as deciding an expense that is already decided, raises SQLSTATE PT409 with a hint (EXPENSE_ALREADY_DECIDED). PostgREST answers that SQLSTATE with HTTP 409, and mapDbError maps it to a conflict error that keeps the hint, so a client calling the function directly and one going through the typed client or an adapter see the same 409. Your own functions can follow the pattern:
if v_row.status <> 'submitted' then
raise exception 'this claim is already decided'
using errcode = 'PT409', hint = 'CLAIM_ALREADY_DECIDED';
end if;Use PT409 when the record's current state refuses the change and a reload shows why: already decided, already running, locked by its status, or a status change the record doesn't allow (EXPENSE_LOCKED, EXPENSE_TRANSITION_INVALID). A precondition outside the record, such as a closed period or a form that isn't published, stays a 55000 error with its own hint. Blocks move their remaining 55000 state refusals to PT409 as they are touched (ADR 1091).
Block hint codes
A block's errors carry a code in hint, such as TASK_LOCKED.
better-supabase/blocks types them: BlockHint<"tasks"> is the union of one
block's codes, and BlockHint the codes of every block. isBlockHint
checks an error against some codes and narrows hint to them; a code no
block raises is a type error. blockHint<"tasks">(error) returns the hint
typed as that block's codes, for an exhaustive switch, without checking
it.
import { blockHint, isBlockHint } from "better-supabase/blocks";
const archived = await blocks.tasks.archive(taskId);
if (!archived.ok && isBlockHint(archived.error, "TASK_LOCKED")) {
toast.error("This task is locked.");
}Custom kinds and mappers
Add mappers for your own RAISE codes:
const betterSupabase = createSupabase(schema, {
errors: [
(raw, fallback) =>
raw.hint === "quota_exceeded"
? dbError("forbidden", fallback.message)
: undefined,
],
});Plugins can also contribute a mapError. These mappers turn a raw
Postgres or PostgREST error into a DbError; the next section turns a
DbError into your own error.
Domain errors for .orThrow()
betterSupabase.mapError(fn) sets the error .orThrow() throws for every db it
connects, instead of a DbException:
export class AppError extends Error {
constructor(readonly error: DbError) {
super(error.message, { cause: error });
}
}
export const toAppError = (error: DbError) => new AppError(error);
export const betterSupabase = createSupabase(schema).mapError(toAppError);
await db.customers.get(id).orThrow(); // throws AppErrorResults themselves keep their DbError, so they stay serializable. The
mapper survives map, mapError and andThen; a factory passed to
.orThrow(factory) takes precedence.
Set the DbError as the error's cause. The server, Next.js, Hono and
oRPC adapters then still answer with Problem Details, and isConflict,
isCheck and isForeignKey still match. TanStack Query hooks always see a
DbException, whatever the mapper.
Map errors by kind and SQLSTATE code
matchDbError builds the factory from one handler per error kind. Handlers
under codes match a SQLSTATE or PostgREST code and run before the handler
for the kind. A handler that returns undefined, and an error with no
handler, throw a DbException.
import { matchDbError } from "better-supabase";
const toAppError = matchDbError({
conflict: (error) => new ConflictError(error.constraint),
forbidden: (error) => new ForbiddenError(error.permission),
not_found: () => new NotFoundError(),
codes: {
"22000": () => new ForbiddenError(),
"23514": (error) => new InvalidError(error.message),
},
});
await db.posts.update(id, patch).orThrow(toAppError);Each kind handler receives the error narrowed to its kind, so error.constraint
is typed for conflict. The result works with betterSupabase.mapError(toAppError)
too.
better-result
To return better-result values
instead, wrap the db with withBetterResult or convert single results with
toBetterResult. See better-result.
Last updated on