Skip to content
VibORM
Esc
↑↓navigate↵open⌘Jpreview
On this page

Errors

Typed error classes, the V#### code taxonomy, and compiler-checked narrowing on error.code

Every failure VibORM raises is a typed class extending VibORMError, carrying a stable V#### code on error.code. You can branch on the class, on the code, or on both — and the compiler checks all three.

Catching

A rejected operation gives you unknown, like every promise. Narrow it first:

import { UniqueConstraintError } from "viborm";

async function register(email: string): Promise<void> {
  try {
    await client.user.create({ data: { email } });
  } catch (error) {
    if (error instanceof UniqueConstraintError) {
      // Provider-specific diagnostics may include constraint, columns, and table.
      throw new Error("That email is already registered.");
    }
    throw error;
  }
}

Constraint metadata depends on the provider’s structured diagnostics. constraint, columns, and table may be absent; handle that case instead of assuming every provider reports them.

isVibORMError(error) narrows to the base class when you want the code without committing to a specific class.

This guard and instanceof use the class identity of your installed VibORM copy. Deduplicate the package across integrations; an error from a second copy does not pass the local guard just because it has the same name or code.

error.code is a literal, and the compiler knows it

Each class declares the exact code it carries, so a union of error types is a discriminated union. Comparing code selects the class:

import type { ForeignKeyError, UniqueConstraintError } from "viborm";

function describeFailure(
  error: UniqueConstraintError | ForeignKeyError
): string {
  if (error.code === "V3001") {
    // error is UniqueConstraintError here
    return `duplicate ${error.meta.columns?.join(", ") ?? "value"}`;
  }
  // and ForeignKeyError here
  return `missing parent for ${error.meta.constraint ?? "relation"}`;
}

Both spellings work in an if: error.code === "V3001" and error.code === VibORMErrorCode.UNIQUE_CONSTRAINT narrow identically. In a switch they do not. case "V3001" compiles but narrows nothing, because a string literal and an enum member are different types to TypeScript even when comparing them is allowed — so reach for VibORMErrorCode whenever you switch, and keep the plain string for one-off ifs where you would rather not add an import.

Because the codes are literals, a comparison that can never be true is a compile error rather than a branch that silently never runs:

import { UniqueConstraintError, VibORMErrorCode } from "viborm";

function handle(error: unknown): string {
  if (
    error instanceof UniqueConstraintError &&
    // @ts-expect-error — a UniqueConstraintError never carries V3002
    error.code === VibORMErrorCode.FOREIGN_KEY_CONSTRAINT
  ) {
    return "unreachable";
  }
  return "ok";
}

Handling a closed set exhaustively

A switch over a union’s codes can be checked for completeness with the usual never guard, so adding a case to the union you handle turns the compiler red instead of falling through:

import { VibORMErrorCode } from "viborm";
import type {
  CheckConstraintError,
  ForeignKeyError,
  NotNullConstraintError,
  UniqueConstraintError,
} from "viborm";

type ConstraintFailure =
  | CheckConstraintError
  | ForeignKeyError
  | NotNullConstraintError
  | UniqueConstraintError;

function userMessage(error: ConstraintFailure): string {
  switch (error.code) {
    case VibORMErrorCode.UNIQUE_CONSTRAINT:
      return "That value is already taken.";
    case VibORMErrorCode.FOREIGN_KEY_CONSTRAINT:
      return "That reference does not exist.";
    case VibORMErrorCode.NOT_NULL_CONSTRAINT:
      return "A required field was empty.";
    case VibORMErrorCode.CHECK_CONSTRAINT:
      return "That value is not allowed.";
    default: {
      const exhaustive: never = error;
      return exhaustive;
    }
  }
}

Retrying

error.isRetryable() identifies failures that may clear on a later attempt: V1001 connection failure, V1002 connection timeout, V1005 exhausted connection capacity, V2002 query timeout, V5003 deadlock, V5004 serialization failure and V5006 lock contention. SQLite SQLITE_BUSY/SQLITE_LOCKED and PostgreSQL 55P03 are contention, distinct from a detected deadlock. MySQL lock-wait timeouts (1205) remain query timeouts. On local libSQL, V5006 also quarantines its client, so a retry there is refused with V1003 until the client is replaced.

Retryability does not prove whether a write committed. Retry a write only when its acknowledgment and idempotency contract make another attempt safe; a rollback-only callback transaction must end before retrying. The helper below assumes the supplied operation is safe to repeat.

import { isRetryableError } from "viborm";

async function withOneRetry<T>(run: () => Promise<T>): Promise<T> {
  try {
    return await run();
  } catch (error) {
    if (!isRetryableError(error)) {
      throw error;
    }
    return await run();
  }
}

Refusals and defects

Two codes in the 8xxx family are worth telling apart from an engine crash, because they look like one and are not:

  • V8003 UnsupportedOperationError — a payload SHAPE the query engine deliberately does not express: a documented capability boundary, or a parity refusal. It is an answer, not a malfunction. It extends QueryEngineError, so an instanceof QueryEngineError check will catch it; branch on the code, or on UnsupportedOperationError itself, when you mean one and not the other. A recursive projection uses it for two properties of the data: Recursive relation '…' contains a cycle. (meta.feature is cyclic recursive traversal), and an output past its occurrence budget, whose message names the operation you ran (meta.feature is recursive output budget).
  • V9001 QueryEngineError — the engine broke its own invariant. That is a bug; please report it (one exception: the malformed driver answer below). A mistake in the payload itself — an empty select (including select: { _count: true } on a model with no to-many relation), a groupBy without a by field, or with a having condition or an orderBy on a field outside by, a JSON null sentinel under a path or in place of a JSON filter — is a V4001 ValidationError whose issue path names the key to fix. The same code reports a driver answer the engine refused to decode, Driver "…" returned a malformed … scalar for operation "…": …., with meta.scalarType naming what was malformed: a value, a row, a relation, or the kind of check a recursive projection’s answer failed, such as recursive depth. That report is not a broken engine invariant: the driver’s answer was malformed, and for a recursive projection the usual cause is a volatile node filter (see Recursive relations).

Everything else in the taxonomy is a refusal of some kind: the database said no, the payload said no, the driver cannot do it, or the record was not there.

The code table

Error class code Raised when
ConnectionError V1001, V1002, V1003, V1005 The database could not be reached, timed out, closed the connection, or exhausted its connection capacity
ClientInitializationError V1004 The client could not be built from the given schema and configuration
QueryError V2001, V2002, V2003, V2004, V2005, V2006, V4002 A statement was rejected, timed out, had invalid syntax, named a missing table/column, exceeded the physical numeric range, returned data outside the declared scalar domain, or violated the raw-input contract
UniqueConstraintError V3001 A unique constraint was violated
ForeignKeyError V3002 A foreign key constraint was violated
NotNullConstraintError V3003 A NOT NULL constraint was violated
CheckConstraintError V3004 A CHECK constraint was violated
ValueTooLongError V3005 A value exceeded the column’s declared length (PostgreSQL and MySQL only)
ValidationError V4001 The payload failed validation before any I/O
SchemaValidationError V4002 The model graph failed schema validation before the client, migration, or query could run
ProviderTransactionContractError V5001 An internal TransactionError subclass reports a provider that violated callback/finalization ordering; catch the public TransactionError family
TransactionError V5001, V5002, V5003, V5004, V5005, V5006 A transaction failed, timed out, deadlocked, lost serialization, was given an option this driver refuses, or encountered lock contention
InvalidTransactionInputError V5005 $transaction([...]) was handed something that is not a pending operation
NotFoundError V6001 An …OrThrow read, or a targeted write, matched no record
NestedWriteError V7001, V7002, V7003, V7004, V7005, V7006 A nested write’s precondition did not hold
NestedWriteAssertionError V7006 A batch-plan precondition (a connect target, an ownership check) did not hold
FeatureNotSupportedError V8001 The driver or dialect does not have the feature (pgvector, PostGIS)
UnsupportedOperationError V8003 A documented shape the query engine does not express
QueryEngineError V9001, V9002 An engine invariant broke, or the schema is not coherent — a bug
CacheInvalidTTLError V10001 A cache TTL was malformed
CacheInvalidKeyError V10002 A cache key could not be built from the payload
CacheOperationNotCacheableError V10003 A write operation was asked to cache
CacheConfigurationError V10004 The cache options or driver are missing or invalid
MigrationError V11001, V11002, V11003, V11004, V11005, V11006, V11007, V11008, V11009, V11010, V11011, V11012, V11013, V11014, V11015, V11016, V11017, V11018, V11019, V11020, V11021, V11022, V11023, plus V4002, V8001, V8002, V9001 A migration failed, is missing, has a checksum or dialect mismatch, could not take the lock, was already applied, arrived out of order, has no file, left an invalid state, was refused as destructive, or needs a storage driver; an estate is invalid, a path is required, live schema drifted, a marker conflicted, an attempt is unfinished, consent is required or stale, a stepwise program left a partial effect, a commit is ambiguous, the provider is unsupported, or artifacts are corrupt, or a PostgreSQL index is INVALID after an interrupted concurrent build or a SurrealDB index failed (or never finished) its build in the background; plus the migration layer’s own refusals of its input, an index type, and an unregistered driver
PendingOperationError V12001, V12002, V12003, V12004 An operation was awaited twice, executed in two ways, or crossed a client or transaction scope
ForbiddenError V13001 A policy refused the operation: the row a write would produce is not permitted, or an explicit permission assertion failed

Codes V4003, V6002 and V6003 are reserved in the taxonomy and are not raised today.

Coming from Prisma

error.prismaCode identifies a Prisma equivalent only for the mapped families. Review each handler when porting: nested-write errors deliberately remain unmapped because their cases span several Prisma categories. Handle them through NestedWriteError and VibORM’s own codes. The mapping table is on the compatibility page.

Validation issues retain their input paths. Provider failures do not guarantee an array-transaction member index or a nested write’s element path; operation and model metadata alone may not identify one failing element.

Error metadata is a bounded, allowlisted diagnostic record. Arbitrary application metadata is not preserved by error construction, logging or serialization. Attach application context in your own logger callback. Statement parameters, when explicitly disclosed, are physical provider values: binary ID carriers are not reconstructed as logical IDs in logs.

Malformed formatted IDs are validation failures on reads as well as writes. A not-found result applies to an admitted ID with no matching row.

V2006 identifies a result outside the declared scalar domain. Its metadata names the model, operation, scalar type, and reason. VibORM refuses the whole query; it does not silently skip or coerce poisoned rows. This is an expected, nonretryable data incompatibility, not an internal engine invariant.

V2004 covers missing tables and columns; V2005 covers numeric overflow in the physical database type. They are not retryable. V1005 names exhausted connection counts and may clear after connections are released. These families intentionally claim no Prisma equivalent: a family can contain more than one Prisma category. Provider codes remain in sanitized metadata, any SQLSTATE-shaped code included (a provider’s own class, such as PlanetScale Neki’s NK013); diagnostics.includeProviderDetails opts into bounded credential-redacted provider message/detail/hint. A PostgreSQL connection that drops under a statement is a retryable ConnectionError V1001, not a refused query.

Was this page helpful?