Error handling
One sentinel per branchable condition, a single error slot with wrap-head semantics, and dialect constraint translation.
Every branchable failure in fusion-orm is a sentinel error checked with
errors.Is — never string matching. Finishers never panic for user errors;
they record the first failure in the chain's single error slot and keep
going until the chain can stop.
The sentinels
// Sentinel errors for every condition the caller must branch on.
// Never string-match these; use errors.Is.| Sentinel | Trigger | Caller action |
|---|---|---|
ErrRecordNotFound | First/Take/Last find no row (errors.go:21). Find returns an empty slice instead. | Branch, or treat as cache-miss. |
ErrMissingWhereClause | Update/Delete without a WHERE unless Config.AllowGlobalUpdate is set (errors.go:25). | Add Where/WherePK, or opt in explicitly to the global write. |
ErrDuplicatedKey | Unique or primary-key constraint, with TranslateError enabled (errors.go:30). | Map to 409-class handling. |
ErrForeignKeyViolated | Foreign-key constraint, with TranslateError (errors.go:31). | Fix referencing rows. |
ErrCheckConstraintViolated | Check constraint, with TranslateError (errors.go:32). | Fix the offending values. |
ErrInvalidValue | Wrong destination or argument type — Find into a non-pointer, a struct where a condition was expected, an empty Updates, a hostile savepoint name (errors.go:34). | Fix the code; this is a programmer error. |
ErrInvalidTransaction | Commit/Rollback outside a transaction; Begin inside one (errors.go:38). | Use Transaction, which nests via savepoints. |
ErrUnsupportedFeature | The active dialect lacks a feature flag the operation needs (errors.go:42). | Dialect-aware fallback; the message names the feature. |
ErrDryRunModeUnsupported | A finisher that requires execution is used while Config.DryRun is set (errors.go:46). | Remove DryRun for that session. |
ErrRegistered | db.Use(plugin) with an already-taken plugin name (errors.go:50, fusion.go:317). | Pick a new name. |
ErrInvalidDB | The connection pool cannot be resolved to a *sql.DB (errors.go:53, fusion.go:369). | Check what you passed as Config.ConnPool. |
ErrInvalidModel | Schema parse failure — the model is not a usable struct (errors.go:58). | Fix the model. |
ErrInvalidTag | Malformed fusion:"..." tag (errors.go:59). | Fix the tag. |
ErrAmbiguousField | Field name cannot be resolved unambiguously (errors.go:60). | Qualify the field. |
ErrInvalidRelation | Relation declaration cannot be honored (errors.go:61). | Fix rel:/foreignKey: tags. |
The constraint sentinels are re-exported from the dialect package, and the
schema sentinels from schema, so callers only import fusion
(errors.go:29, errors.go:57).
var got User
err := db.First(&got, 999).Error
if errors.Is(err, fusion.ErrRecordNotFound) {
// no row matched
}Sentinels are distinct
The package tests assert that no sentinel errors.Is-matches another, so a
switch on these values is total (errors_test.go:88).
The single error slot
Every *DB carries one Error field. AddError records onto it with
wrap-chain semantics (errors.go:83):
// AddError records err on db's single error slot using wrap-chain
// semantics: the first error is kept as the wrap head so errors.Is continues
// to match it, and subsequent errors are appended with "; %w" so every cause
// stays branchable. Returns the full chain (nil when err is nil).Concretely: the first error becomes the head of the chain; every later error
is joined with "; %w". Both causes stay branchable — the head is never
lost, and later errors still match too (errors_test.go:25-44):
db.AddError(first) // db.Error wraps first
db.AddError(second) // joined: errors.Is matches first AND secondAddError(nil) is a no-op (errors_test.go:46).
Error translation
Driver constraint errors are driver-specific. With
Config.TranslateError: true, AddError hands each error to the dialector's
Translate before recording it (errors.go:88-96). The shipped dialectors
map:
| Dialect | Driver signal | Sentinel |
|---|---|---|
| PostgreSQL | SQLSTATE 23505 | ErrDuplicatedKey |
| PostgreSQL | SQLSTATE 23503 | ErrForeignKeyViolated |
| PostgreSQL | SQLSTATE 23514 | ErrCheckConstraintViolated |
| SQLite | SQLITE_CONSTRAINT_UNIQUE / _PRIMARYKEY | ErrDuplicatedKey |
| SQLite | SQLITE_CONSTRAINT_FOREIGNKEY | ErrForeignKeyViolated |
| SQLite | SQLITE_CONSTRAINT_CHECK | ErrCheckConstraintViolated |
Translation wraps rather than replaces — the driver error stays in the chain
as a second %w cause (dialect/postgres/postgres.go:101). With translation
off, the raw driver error is recorded untouched (errors_test.go:64-72).
db, _ := fusion.Open(sqlite.Open(dsn), &fusion.Config{TranslateError: true})
db.Exec(`CREATE TABLE uniq_users (id INTEGER PRIMARY KEY, email TEXT UNIQUE)`)
db.Exec(`INSERT INTO uniq_users (email) VALUES ('a')`)
err := db.Exec(`INSERT INTO uniq_users (email) VALUES ('a')`).Error
if errors.Is(err, fusion.ErrDuplicatedKey) {
// unique violation, translated
}Translation is a dialector capability
ErrorTranslator is an optional interface a custom dialector may implement.
If TranslateError is enabled but the dialector does not, Open logs a
warning and errors pass through untranslated (fusion.go:222-227).
UnsupportedFeatureError
When a dialect lacks a capability, the error both matches
ErrUnsupportedFeature and names the feature, so you can branch generically
while logging precisely what was missing (errors.go:64):
err := fusion.NewUnsupportedFeatureError("CompositeIn")
errors.Is(err, fusion.ErrUnsupportedFeature) // true
errors.As(err, &target) // target.Feature == "CompositeIn"
err.Error() // "unsupported feature: CompositeIn"For example, savepoints require feature.Savepoint; a dialector without it
records this error instead of executing (transaction.go:150). The migrator
has its own migrator.ErrUnsupportedFeature for schema operations
(migrator/migrator.go:103).
Every error path in one table
The library's own test suite pins the common paths in a table you can skim as a behavioral contract (error_paths_test.go:22):
| Scenario | Expected sentinel |
|---|---|
First on a missing primary key | ErrRecordNotFound |
Update with no conditions | ErrMissingWhereClause |
Delete with no conditions | ErrMissingWhereClause |
Updates(nil) | ErrInvalidValue |
Where(42) (invalid condition) | ErrInvalidValue |
SavePoint("bad name!") | ErrInvalidValue |
Commit without a transaction | ErrInvalidTransaction |
Rollback without a transaction | ErrInvalidTransaction |
tests := []struct {
name string
want error
run func() error
}{
{name: "record not found", want: ErrRecordNotFound, run: func() error {
var user errPathUser
return db.First(&user, 999).Error
}},
// ...
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if err := tt.run(); !errors.Is(err, tt.want) {
t.Errorf("error = %v, want %v", err, tt.want)
}
})
}