Go · Level 2 Errors

Wrapping Errors

Wrap a sentinel error with fmt.Errorf and %w in Go to add context like the user ID, and check it with errors.Is, because == no longer matches a wrapped error.

  • a sentinel error: var ErrNotFound
  • %w wraps and keeps the cause
  • errors.Is looks inside, == doesn't

fmt.Errorf("user %d: %w", id, err) adds context and keeps the original error inside. Trap: after wrapping, err == ErrNotFound is false; errors.Is(err, ErrNotFound) looks inside and finds it.

var ErrNotFound = errors.New("not found")
err := fmt.Errorf("order 7: %w", ErrNotFound)
err == ErrNotFound           // false
errors.Is(err, ErrNotFound)  // true

Write FindUser(users map[int]string, id int) (string, error): the name, or "" and ErrNotFound wrapped as "user <id>: not found". Example: FindUser(map[int]string{}, 7) → "", user 7: not found.

solution.go
Test Suites Pending
Output