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
| Class | Thrown when | Useful fields |
|---|---|---|
ValidationError | A model validator, allowNull: false or a type check fails before the query runs | errors (ValidationErrorItem[]: path, message, type, value, origin) |
UniqueConstraintError (extends ValidationError) | 23505 unique violation | fields, errors, parent, sql |
DatabaseError | Any other server error | parent (the pg error, parent.code), sql, parameters |
ForeignKeyConstraintError (extends DatabaseError) | 23503 foreign key violation | table, fields, index (constraint name) |
ExclusionConstraintError (extends DatabaseError) | 23P01 exclusion violation | constraint, 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 DatabaseError | constraint, table |
TimeoutError (extends DatabaseError) | 57014 the statement was cancelled (statement_timeout, statementTimeout) | as DatabaseError |
EmptyResultError | rejectOnEmpty found no row | |
OptimisticLockError | Saving a stale instance of a model with version: true | modelName, where, values |
ConnectionError and subclasses | The connection could not be made or was lost | parent |
AggregateError, BulkRecordError, EagerLoadingError, InstanceError, AssociationError, SequelizeScopeError, QueryError | Library-level problems: failed bulk records, bad include, wrong instance use, unknown scope | per 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:
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
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.
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:
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:
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.
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.
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
Error(the base class, also exported asBaseError),ValidationError,ValidationErrorItem,UniqueConstraintErrorDatabaseError,ForeignKeyConstraintError,ExclusionConstraintError,TimeoutErrorConnectionError,EmptyResultError,OptimisticLockError