Skip to Content
fusion-orm

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.
SentinelTriggerCaller action
ErrRecordNotFoundFirst/Take/Last find no row (errors.go:21). Find returns an empty slice instead.Branch, or treat as cache-miss.
ErrMissingWhereClauseUpdate/Delete without a WHERE unless Config.AllowGlobalUpdate is set (errors.go:25).Add Where/WherePK, or opt in explicitly to the global write.
ErrDuplicatedKeyUnique or primary-key constraint, with TranslateError enabled (errors.go:30).Map to 409-class handling.
ErrForeignKeyViolatedForeign-key constraint, with TranslateError (errors.go:31).Fix referencing rows.
ErrCheckConstraintViolatedCheck constraint, with TranslateError (errors.go:32).Fix the offending values.
ErrInvalidValueWrong 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.
ErrInvalidTransactionCommit/Rollback outside a transaction; Begin inside one (errors.go:38).Use Transaction, which nests via savepoints.
ErrUnsupportedFeatureThe active dialect lacks a feature flag the operation needs (errors.go:42).Dialect-aware fallback; the message names the feature.
ErrDryRunModeUnsupportedA finisher that requires execution is used while Config.DryRun is set (errors.go:46).Remove DryRun for that session.
ErrRegistereddb.Use(plugin) with an already-taken plugin name (errors.go:50, fusion.go:317).Pick a new name.
ErrInvalidDBThe connection pool cannot be resolved to a *sql.DB (errors.go:53, fusion.go:369).Check what you passed as Config.ConnPool.
ErrInvalidModelSchema parse failure — the model is not a usable struct (errors.go:58).Fix the model.
ErrInvalidTagMalformed fusion:"..." tag (errors.go:59).Fix the tag.
ErrAmbiguousFieldField name cannot be resolved unambiguously (errors.go:60).Qualify the field.
ErrInvalidRelationRelation 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 second

AddError(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:

DialectDriver signalSentinel
PostgreSQLSQLSTATE 23505ErrDuplicatedKey
PostgreSQLSQLSTATE 23503ErrForeignKeyViolated
PostgreSQLSQLSTATE 23514ErrCheckConstraintViolated
SQLiteSQLITE_CONSTRAINT_UNIQUE / _PRIMARYKEYErrDuplicatedKey
SQLiteSQLITE_CONSTRAINT_FOREIGNKEYErrForeignKeyViolated
SQLiteSQLITE_CONSTRAINT_CHECKErrCheckConstraintViolated

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):

ScenarioExpected sentinel
First on a missing primary keyErrRecordNotFound
Update with no conditionsErrMissingWhereClause
Delete with no conditionsErrMissingWhereClause
Updates(nil)ErrInvalidValue
Where(42) (invalid condition)ErrInvalidValue
SavePoint("bad name!")ErrInvalidValue
Commit without a transactionErrInvalidTransaction
Rollback without a transactionErrInvalidTransaction
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)
		}
	})
}

Next

On this page