Classify database errors and retries
Classify database errors and retries
Distinguish sql.ErrNoRows, context cancellation, permanent errors and transient conflicts. Actual engine codes require driver documentation. Retry a whole transaction only when failure semantics permit it and the operation is safe to repeat. A lost commit response can leave the outcome unknown.
package main
import ( "context" "database/sql" "errors" "fmt")
var errConflict = errors.New("fixture conflict")
func retryable(err error) bool { return errors.Is(err, errConflict) }func retry(ctx context.Context, n int, run func() error) error { if n < 1 { return errors.New("invalid limit") } for i := 0; i < n; i++ { if err := ctx.Err(); err != nil { return err } err := run() if err == nil || !retryable(err) || i == n-1 { return err } } return errors.New("unreachable")}func main() { fmt.Println(retryable(fmt.Errorf("update: %w", errConflict))) fmt.Println(retryable(sql.ErrNoRows)) fmt.Println(retryable(context.Canceled))}The sentinel is synthetic, not a real database code. Use errors.Is or errors.As with documented driver errors, not message matching. Do not retry unknown commit outcomes blindly.
Expected output:
truefalsefalseBound the attempts
package main
import ( "context" "errors" "fmt")
var errConflict = errors.New("fixture conflict")
func retryable(err error) bool { return errors.Is(err, errConflict) }func retry(ctx context.Context, n int, run func() error) error { if n < 1 { return errors.New("invalid limit") } for i := 0; i < n; i++ { if err := ctx.Err(); err != nil { return err } err := run() if err == nil || !retryable(err) || i == n-1 { return err } } return errors.New("unreachable")}func main() { n := 0 err := retry(context.Background(), 3, func() error { n++ if n == 1 { return errConflict } return nil }) fmt.Println(n, err == nil)}The callback should create a fresh transaction per attempt. Production needs capped backoff with jitter, cancellation-aware waiting, a time budget and repeatable external effects. This fixture demonstrates only the attempt limit.
Expected output:
2 trueTry it locally
Always return errConflict; with two attempts print count and whether the final error is the conflict sentinel.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Database 07: Classify database errors and retries
Check the lesson objective before moving on.
Which operation can be retried automatically?
Why bound attempts?