Unique keys and errors
get by any unique key, typed constraint names, and narrowing database errors.
Unique keys
get takes the primary key or any unique key, as columns in your casing. gen reads the unique constraints and indexes, so a where that
isn't a complete key is a type error.
await db.customers.get({ id }, { optional: true });
await db.customers.get({ organizationId, kvk }, { optional: true }); // customers_organization_id_kvk_key
// @ts-expect-error kvk alone is not unique
await db.customers.get({ kvk }, { optional: true });With optional: true it returns the row or null; without it, a missing row
fails with not_found. get(id) is the primary key shortcut.
Constraint names
The generated module exports the names of your constraints:
import type {
CheckConstraint,
ForeignKeyConstraint,
UniqueConstraint,
} from "./generated";Pass them to the error guards to narrow an error to one constraint, with a type error on typos:
import { isCheck, isConflict, isForeignKey } from "better-supabase";
const result = await db.customers.create({ organizationId, name, kvk });
if (
isConflict<UniqueConstraint>(
result.error,
"customers_organization_id_kvk_key",
)
) {
return { field: "kvk", message: "This KvK number is already registered" };
}
if (isCheck<CheckConstraint>(result.error)) {
return { message: `Invalid value (${result.error.constraint})` };
}
if (
isForeignKey<ForeignKeyConstraint>(
result.error,
"customers_primary_contact_id_fkey",
)
) {
return { field: "primaryContactId", message: "Pick an existing contact" };
}The guards accept a DbError, a DbException or anything else (they
return false), so they also work in a catch block.
Error kinds
Every failure is a DbError with a kind:
| Kind | Cause |
|---|---|
conflict | Unique violation (constraint is set) |
check | CHECK violation (constraint is set) |
foreign_key | Foreign key violation (constraint is set) |
not_null | Missing required value |
not_found | get, update(id) or delete(id) matched no row |
forbidden | RLS or a missing grant |
validation | A validator plugin or a jsonb-schemas check rejected the input (issues is set) |
invalid_input | A block function rejected an input (fields names each one, when it knows) |
invalid_request | Caught before the request: a read-only column, an unknown field, a broken rule |
See Results for the full list and how errors map to HTTP Problem Details.
Block errors in forms
A block function that rejects its input returns an invalid_input error
with fields: one { path, code, message } per input at fault. The path
is where the input sits in the call (["lines", 0, "quantity"]), the code
is an upper snake case code like a hint code, and the message is English.
toProblem sends fields as an extension member, so a client that reads
the Problem Details body gets them back.
import { invalidInput } from "better-supabase";
const error = invalidInput("A tag needs a name", [
{ path: ["name"], code: "TAG_NAME_REQUIRED", message: "A tag needs a name" },
]);A SQL function can raise the same list: use an 22xxx SQLSTATE and put
{"fields": [{"path": ["name"], "code": "NAME_REQUIRED", "message": "..."}]}
in the DETAIL.
Every hint code a block raises has a default English message.
better-supabase/blocks/messages exports them as BLOCK_HINT_MESSAGES,
keyed by code, so the code is also the next-intl key:
import {
BLOCK_HINT_MESSAGES,
blockErrorMessage,
fieldMessages,
} from "better-supabase/blocks/messages";
// messages/en.ts: { blockErrors: BLOCK_HINT_MESSAGES }
const translate = (code: string, english: string) =>
t.has(`blockErrors.${code}`) ? t(`blockErrors.${code}`) : english;
blockErrorMessage(result.error, translate); // the sentence, or undefined
fieldMessages(result.error, translate); // { name: "A tag needs a name" }createBlocks also takes locale and hintMessages. When hintMessages is set,
it rewords the message of every error a block's SQL raises with a hint
code, and each block creator reads locale from its options. The error's
hint and kind never change, only message. Errors a block's TypeScript
raises keep their English message; word them with blockErrorMessage.
createBlocks(blocks, {
transport,
locale: "nl",
hintMessages: (hint, locale, english) => dutch[hint],
});Throwing your own errors
.orThrow() throws a DbException. It carries the plain DbError as
error and as cause, and copies the fields you usually branch on or log
onto the exception itself:
| Field | Value |
|---|---|
message | the error's message |
kind | the DbError kind (not_found, conflict, ...) |
status | the suggested HTTP status |
code | the SQLSTATE or PostgREST code (23505, PGRST116), when known |
details | the Postgres DETAIL, when present |
hint | the Postgres HINT, when present |
table | the app-cased table key, when known |
These are own, enumerable fields, so error trackers and loggers that
serialize an error's own properties record them. The kind-specific fields,
such as constraint on a conflict, stay on error. The guards
(isConflict, isNotFound) and dbErrorOf() accept the exception
directly, and isDbError() is false for it, because it is an Error
rather than plain data.
try {
await db.customers.create(input).orThrow();
} catch (exception) {
if (exception instanceof DbException && exception.code === "23505") {
// a unique violation; exception.error.constraint names it
}
throw exception;
}Pass a factory to throw something your framework understands instead:
const customer = await db.customers
.get(id)
.orThrow((error) =>
error.kind === "not_found" ? notFound() : new Error(error.message),
);Read-only columns
Generated columns, identity always columns and view columns Postgres
marks as not insertable or updatable are missing from the Insert and
Update types. Writing one anyway (through as any or a spread) fails with
invalid_request before a request is sent, instead of a database error.
Last updated on