Errors

Every store and driver throws the same exceptions: a duplicate key is a DuplicateKeyException in memory, on SQLite and on PostgreSQL. They follow Spring's DataAccessException hierarchy, so code that catches a supertype (ConcurrencyFailureException to retry, DataIntegrityViolationException to answer a 409) works whatever the database.

Why

A SQLite error code, a PostgreSQL SQL state and an in-memory check say the same thing in three ways. Translated into one hierarchy, your services handle "this title already exists" or "someone else changed this row" once, and a test on the in-memory store throws what production throws.

Example

@Service()
class Authors {
  Authors(this.authors);

  final AuthorRepository authors;

  Future<Author> register(String name) async {
    try {
      return await authors.save(Author(name: name));     // name is @Unique
    } on DuplicateKeyException {
      throw NameTaken(name);
    }
  }

  // Retry what failed because of another transaction.
  Future<T> retrying<T>(Future<T> Function() work) async {
    for (var attempt = 1;; attempt++) {
      try {
        return await work();
      } on ConcurrencyFailureException {
        if (attempt == 3) rethrow;
      }
    }
  }
}

Data access exceptions

Exception Parent When
DataAccessException The root, abstract.
TransientDataAccessException DataAccessException May succeed if tried again.
NonTransientDataAccessException DataAccessException Will fail again.
DataIntegrityViolationException non-transient A constraint: a missing referenced aggregate, a NOT NULL, a check.
DuplicateKeyException DataIntegrityViolationException A primary or unique key taken.
IncorrectResultSizeDataAccessException non-transient More than one row where one was expected.
EmptyResultDataAccessException IncorrectResultSizeDataAccessException No row where one was required.
IncorrectUpdateSemanticsDataAccessException InvalidDataAccessResourceUsageException save updated no row for an entity without @Version whose row is gone.
InvalidDataAccessResourceUsageException non-transient The resource used wrongly: a write in a read-only transaction.
PermissionDeniedDataAccessException non-transient The database refused the statement for a missing privilege, or for a row-level security policy that refuses the row written (PostgreSQL's 42501).
BadSqlGrammarException InvalidDataAccessResourceUsageException Wrong SQL: syntax, an unknown table or column.
InvalidDataAccessApiUsageException non-transient The API used wrongly.
InvalidDataArgumentException InvalidDataAccessApiUsageException The caller's value refused: a NUL in text, an In list too long, a LIKE pattern the database rejects.
PropertyReferenceException InvalidDataAccessApiUsageException A sort property the entity does not have.
DataAccessResourceFailureException non-transient The database cannot be reached: a lost connection, authentication, a missing database.
ConcurrencyFailureException transient Another transaction got in the way: retry.
OptimisticLockingFailureException ConcurrencyFailureException A @Version conflict.
PessimisticLockingFailureException ConcurrencyFailureException A lock problem.
CannotAcquireLockException PessimisticLockingFailureException A lock not had in time (NOWAIT, a timeout, SQLite busy).
DeadlockLoserDataAccessException PessimisticLockingFailureException Chosen as a deadlock's victim.
CannotSerializeTransactionException PessimisticLockingFailureException A serialization failure under repeatableRead or serializable.
QueryTimeoutException transient A statement past its timeout.
InvalidPagingRequestException ArgumentError A negative page, a size below one, an offset past 2^53 - 1.
MappingException InvalidDataAccessApiUsageException An entity that cannot be mapped: no @Id and no @Version, a field of an entity type, a wrong @Reference type.

Messages carry the database's message, never a bound value or a password.

Transaction exceptions

Exception When
IllegalTransactionStateException mandatory without a transaction, never within one, a @Lock query outside a transaction, work that outlived its transaction.
UnexpectedRollbackException The commit found the transaction marked rollback-only (a joined method failed, a timeout).
TransactionSystemException The commit or rollback itself failed; applicationException holds the method's error.
TransactionTimedOutException The transaction ran past its timeout.
CannotCreateTransactionException The transaction could not begin.
NestedTransactionNotSupportedException nested on a store without savepoints.
InvalidIsolationLevelException An isolation level the store does not offer.
InvalidTimeoutException A negative timeout.

Schema exceptions

Exception When
SchemaException The root, a NonTransientDataAccessException.
ScriptException A statement of schema.sql or data.sql failed (file and line).
MigrationException A migration failed, or the history does not match the files.
SchemaValidationException The entities do not fit the tables (spring.data.jdbc.schema=validate).

These stop the start. The dataFailureAnalyzer bean turns them, and a URL no driver handles, into a startup report that explains the cause and the fix. The bean is a startup check, in the build by spring.main.startup-checks.enabled: not set, in debug and profile builds only, so a release build ships none of its code and a database that fails the start is reported as it was thrown. true in application.yml or application.properties keeps it in every build, false in none.

In a web application

With the web starter, the generated dataAccessExceptionResolver answers some of these with a status and a fixed detail (see In a web application): 409 for OptimisticLockingFailureException and DuplicateKeyException, 404 for EmptyResultDataAccessException, 403 for PermissionDeniedDataAccessException, 400 for PropertyReferenceException, InvalidPagingRequestException and InvalidDataArgumentException. Others are a 500.

In Spring (Java)

The class names are Spring's (org.springframework.dao, org.springframework.transaction). Two differences:

See also