Errors
Match errors with errors.Is and errors.As, never by their text. Builders collect errors while you chain. The call that runs the query returns them, joined if there are several.
user, err := db.Users.Find(ctx, id)
if errors.Is(err, ant.ErrNotFound) {
return nil
}
Reading rows
| Error | Means |
|---|---|
ant.ErrNotFound | First, Single, Find or Reload found no row |
ant.ErrMultipleRows | Single found more than one |
ant.ErrUnknownColumn | A result column has no field, under WithStrict |
ant.ErrCursor | A page cursor this query cannot use |
ant.ErrIncludeInEach | Each with Include, which would need a second query while rows stream. Use All, or Chunk |
ant.ErrIncludeInSubquery | A subquery with Include |
ant.ErrNoColumns | A query whose selection leaves no columns |
Writing rows
| Error | Means |
|---|---|
ant.ErrNoCondition | A bulk write with no condition that can exclude a row. Unfiltered allows it on purpose |
ant.ErrNoAssignment | An Update with nothing to set |
ant.ErrNoRows | A write given no rows |
ant.ErrNilEntity | A nil pointer passed to a write |
ant.ErrReadOnly | A write to a read-only model, such as a view |
ant.ErrNotSoftDeleted | Restore on a model with no DeletedAt |
ant.ErrNotManyToMany | Link or Unlink on another kind of relation |
ant.ErrCycle | New entities that depend on each other, so neither can be inserted first. Save them in two steps |
Using the wrong field or key
| Error | Means |
|---|---|
ant.ErrNotProbe | A pointer that does not come from a probe |
ant.ErrWrongModel | A field pointer from another model's probe |
ant.ErrNotColumn | A relation used as a column |
ant.ErrNotRelation | A field that is not a relation, used as one |
ant.ErrNoKey | A key operation on a model with no primary key |
ant.ErrKeyType | A key whose type does not match the primary key |
antvet finds most of these at build time.
Setup
| Error | Means |
|---|---|
ant.ErrNoContext | The type passed to Open does not embed ant.Context |
ant.ErrNotOpen | A table or context that did not come from Open |
ant.ErrNoForeignKey | A relation whose foreign key cannot be found by convention. Name it in Configure |
ant.ErrNoColumnType | A field whose database type cannot be worked out. Set it with Column(...).Type(...) |
ant.ErrBadSchema | Models that cannot become a valid schema |
ant.ErrNotImplemented | A feature with no implementation yet |
Change tracking and transactions
| Error | Means |
|---|---|
ant.ErrConcurrency | A version or token check failed. See stale writes |
ant.ErrConcurrentUse | A context with change tracking was used by two operations at once. See a tracking context used twice |
ant.ErrKeyChanged | The primary key of a tracked entity was changed. Insert a new entity instead |
ant.ErrNotTracked | An operation on an entity the context does not track |
ant.ErrNotInTx | Commit, Rollback or a savepoint outside a transaction |
ant.ErrTxDone | The transaction already ended |
ant.ErrTxType | A Tx closure whose parameter is not this context's type |
Stale writes
ant.ErrConcurrency comes back from SaveChanges and from an Upsert of a copy that carries a version, on every database including MySQL and MariaDB. It is an *ant.ConcurrencyError naming the row:
_, err := db.Pages.Upsert(ctx, stale, ant.OnConflict(&Pages.Slug))
var conflict *ant.ConcurrencyError
if errors.As(err, &conflict) {
fmt.Println(conflict.Model, conflict.Key)
}
A tracking context used twice
If a second operation starts on a tracking context while the first runs, the second gets ant.ErrConcurrentUse at once without waiting. Give each request its own ant.Session, or share a context opened with WithTracking(false). A query that a hook makes must use the context.Context the hook received. See sessions and hooks.
Unsupported on this database
ant.ErrUnsupported means the connected database cannot do what you asked. ant refuses before sending SQL.
_, err := ant.Merge(&db.Users, db.Posts.Query(), ant.EqCol(&Users.ID, &Posts.UserID)).
WhenMatched(ant.Set(&Users.Age, 1)).
Exec(ctx)
// ant: not supported by this database: MERGE on mysql
Cases beyond the feature table in databases:
- A write after
FromCTEorRecursiveon SQL Server, which takes noWITHinside a subquery. - On MySQL, a write whose subquery reads the table being written and uses
SELECT *beside other columns, or over a join or a set. - On MySQL,
InsertManywith aSetthat reads its own table and a column left to its default. - An upsert with no conflict columns on a database that needs them.
Check first:
if dialect.Supports(db.Dialect(), dialect.Merge) {
// ...
}
Naming a column twice
PostgreSQL and SQL Server refuse a write that gives a column two values. MySQL keeps the last. ant refuses it before any SQL runs, on every database. It covers DoUpdate and Set of an upsert, a bulk Update, UpdateMany, a merge's WhenMatched and WhenNotMatched, and the mappings of InsertFrom.
_, err := db.Users.Where(ant.Eq(&Users.ID, id)).Update(ctx, ant.Set(&Users.Name, "x"), ant.Set(&Users.Name, "y"))
// ant: User.Name has two assignments; give it one
Naming a version field in any of those is refused too, since ant moves it on by itself. UpdatedAt is the exception: the value you give wins over ant's.
Validation errors
A failed field rule is an *ant.ValidationError with Model, Field and Err. It unwraps to the rule's error.
Database errors
These classify a database's error on all five databases.
err := db.Users.Insert(ctx, user)
switch {
case ant.IsUniqueViolation(err):
return errors.New("already exists")
case ant.IsForeignKeyViolation(err):
return errors.New("refers to something missing")
case ant.IsNotNullViolation(err), ant.IsCheckViolation(err):
return errors.New("invalid")
case ant.IsRetryable(err):
return errors.New("try again")
}
ant.SQLState(err) returns the code itself, such as 23505. Each dialect translates its own codes.
| Function | SQLSTATE |
|---|---|
ant.IsUniqueViolation | 23505 |
ant.IsForeignKeyViolation | 23503 |
ant.IsNotNullViolation | 23502 |
ant.IsCheckViolation | 23514 |
ant.IsRetryable | 40001 (serialization failure) and 40P01 (deadlock) |
IsRetryable is true for MySQL and MariaDB deadlocks, and for MariaDB error 1020, which MariaDB 11.6 and later raise when a row changed since the transaction's snapshot. MariaDB rolls the transaction back, so run it again from the start.
Retry a transaction
func transfer(ctx context.Context, db *AppDB) error {
var err error
for range 3 {
err = db.Tx(ctx, func(tx *AppDB) error {
// ... reads and writes
return nil
})
if !ant.IsRetryable(err) {
return err
}
}
return err
}
Find the failing statement
ant.FailedSQL returns the statement behind a query error, with placeholders and no values, so it is safe for an internal log.
err := db.Users.Insert(ctx, user)
slog.Error("insert failed", "sql", ant.FailedSQL(err))
ant.WithDetailedErrors() adds the statement to every error's message. Leave it off where errors reach users. A database error's message can also quote a value, so do not return err.Error() to a client.
Strict scanning
By default a result column with no field is ignored. ant.WithStrict() returns ant.ErrUnknownColumn instead.
db, err := ant.Open[AppDB](ctx, postgres.Dialect, dsn, ant.WithStrict())
ant.WithLooseScan() switches WithStrict back off, for code that builds options in layers.
See it tested: tests/features/developer_tooling/errors_test.go