Skip to content

Errors ​

postgrelize throws the Sequelize v6 error classes, exported from the package root, so instanceof checks and error.name strings from v6 code keep working. Constraint violations, validation failures, timeouts and connection problems each have their own class; everything the server rejects that has no specific class is a DatabaseError. The original pg error is always available as error.parent (also error.original), with the PostgreSQL error code, constraint, table, detail and the rest of its fields.

Class hierarchy ​

ClassThrown whenUseful fields
ValidationErrorA model validator, allowNull: false or a type check fails before the query runserrors (ValidationErrorItem[]: path, message, type, value, origin)
UniqueConstraintError (extends ValidationError)23505 unique violationfields, errors, parent, sql
DatabaseErrorAny other server errorparent (the pg error, parent.code), sql, parameters
ForeignKeyConstraintError (extends DatabaseError)23503 foreign key violationtable, fields, index (constraint name)
ExclusionConstraintError (extends DatabaseError)23P01 exclusion violationconstraint, fields, table
UnknownConstraintError (extends DatabaseError)Exported for v6 compatibility (a constraint that does not exist was referenced); the library itself reports a missing constraint as a plain DatabaseErrorconstraint, table
TimeoutError (extends DatabaseError)57014 the statement was cancelled (statement_timeout, statementTimeout)as DatabaseError
EmptyResultErrorrejectOnEmpty found no row
OptimisticLockErrorSaving a stale instance of a model with version: truemodelName, where, values
ConnectionError and subclassesThe connection could not be made or was lostparent
AggregateError, BulkRecordError, EagerLoadingError, InstanceError, AssociationError, SequelizeScopeError, QueryErrorLibrary-level problems: failed bulk records, bad include, wrong instance use, unknown scopeper class

ConnectionError subclasses: ConnectionRefusedError, AccessDeniedError, HostNotFoundError, HostNotReachableError, InvalidConnectionError, ConnectionTimedOutError, ConnectionAcquireTimeoutError (the pool had no free connection within pool.acquire). The error.name of each keeps the v6 spelling (SequelizeUniqueConstraintError, ...).

Unique violations ​

fields maps the violated columns to the offered values, and errors has one ValidationErrorItem per column, so the same code can show per-field messages for both validation and unique failures:

ts
try {
  await Author.create({ email: 'ann@example.com', name: 'Ann again' });
} catch (error) {
  if (!(error instanceof UniqueConstraintError)) throw error;
  // error.fields: { email: 'ann@example.com' }
  // error.errors[0].type === 'unique violation', error.errors[0].path === 'email'
  // error.parent.code === '23505': the original pg error
  if (error.fields.email !== 'ann@example.com')
    throw new Error('unexpected fields', { cause: error });
}

Foreign key violations ​

ts
try {
  await Book.create({ title: 'Orphan', authorId: 999 });
} catch (error) {
  if (!(error instanceof ForeignKeyConstraintError)) throw error;
  // error.table === 'Authors', error.index is the constraint name, error.fields lists the columns
  if (error.parent.code !== '23503') throw new Error('unexpected code', { cause: error });
}

Validation errors ​

Validators run before the query; the error lists every failing attribute, not just the first. See Hooks and validation for the validators themselves.

ts
try {
  await Author.create({ email: 'bob@example.com', name: 'B' });
} catch (error) {
  if (!(error instanceof ValidationError)) throw error;
  for (const item of error.errors) {
    // item.path === 'name', item.type === 'Validation error', item.message, item.value === 'B'
    if (item.path !== 'name') throw new Error('unexpected path', { cause: error });
  }
}

Missing rows ​

findOne, findByPk and findAll resolve to null or [] by default. Pass rejectOnEmpty: true (or an Error instance to throw your own) to turn a missing row into an exception:

ts
const missing = await Author.findOne({
  where: { email: 'nobody@example.com' },
  rejectOnEmpty: true,
})
  .then(() => null)
  .catch((error: unknown) => error);
if (!(missing instanceof EmptyResultError)) throw new Error('expected EmptyResultError');

Optimistic locking ​

Set version: true in the model options and every update becomes UPDATE ... WHERE id = $1 AND version = $2. A second writer holding an older copy gets an OptimisticLockError instead of silently overwriting the first:

ts
const ticket = await Ticket.create({ subject: 'printer' });
const sameTicket = await Ticket.findByPk(ticket.get('id') as number);
await ticket.update({ subject: 'printer on fire' });
const stale = await sameTicket!.update({ subject: 'paper jam' }).catch((error: unknown) => error);
if (!(stale instanceof OptimisticLockError)) throw new Error('expected OptimisticLockError');

Timeouts postgrelize extension ​

statementTimeout is a postgrelize option that cancels one slow statement on the server and throws TimeoutError; the connection stays usable for the next query. TimeoutError is a DatabaseError, so a generic handler still catches it.

ts
const slow = await sequelize
  .query('SELECT pg_sleep(5)', { statementTimeout: 50 })
  .catch((error: unknown) => error);
if (!(slow instanceof TimeoutError)) throw new Error('expected TimeoutError');
// TimeoutError extends DatabaseError, so a generic handler still catches it
if (!(slow instanceof DatabaseError)) throw new Error('TimeoutError is a DatabaseError');

Any other server error ​

Everything without a dedicated class is a DatabaseError. Branch on error.parent.code (the SQLSTATE) when you need to tell them apart: 40001 serialization failure and 40P01 deadlock (retry the whole transaction), 55P03 lock not available (noWait), 22012 division by zero, 42P01 undefined table.

ts
const bad = await sequelize.query('SELECT 1 / 0').catch((error: unknown) => error);
if (!(bad instanceof DatabaseError)) throw new Error('expected DatabaseError');
// bad.parent.code === '22012' (division_by_zero), bad.sql is the statement that failed
if (bad.parent.code !== '22012') throw new Error('unexpected code');

Retrying is up to the application, or use the retry option for connection and transaction-start failures. Errors inside a transaction abort it: roll back and run the transaction again.

API reference ​

Released under the MIT License.