Wrapping, Is, and As

"%w" keeps the chain. Is looks for a sentinel. As pulls out a concrete type.

fmt.Errorf("save user: %w", err) wraps an error. The text gets longer, and the original error stays inside. errors.Is(err, ErrNotFound) walks the chain and finds the sentinel, even if it was wrapped three times. %v instead of %w also appends text, but it breaks the chain: Is will no longer see the original error. Wrappers almost always need %w.

errors.As pulls out an error of a concrete type:

var pathErr *os.PathError
if errors.As(err, &pathErr) {
    // можно смотреть pathErr.Path
}

You introduce a type when the caller needs fields, not a single fact "this situation". The fields are exported and documented. An empty error type with no data is worse than a sentinel: it is harder to create and there is nothing to read from it.

Sentinels are compared by value identity. Two errors.New("missing") are not equal, even if the text is the same. errors.Is does not compare strings.

var ErrMissing = errors.New("missing")

func IsMissing(err error) bool {
    return errors.Is(err, ErrMissing)
}

IsMissing(fmt.Errorf("read: %w", ErrMissing)) is true. IsMissing(errors.New("missing")) is false: that is a different error with the same text.

Add context that exists only at this level: the operation name, an id. Do not write "error:" at the start of every wrapper. And do not wrap nil: fmt.Errorf("x: %w", nil) returns a non-nil error, and the caller will decide that the call failed.

Practice

  1. Which format verb

    Which format keeps the original error for errors.Is?

    • %v
    • %w
    • %s
    • %q
  2. Recognize your own error

    Declare a package variable ErrMissing with errors.New("missing"). Write IsMissing(err error) bool, which is true for ErrMissing and for an error wrapped around it with %w. A foreign error with the same text, and nil, must give false.

  3. Wrapping nil

    What is the result of fmt.Errorf("load: %w", nil) from the point of view of err != nil?

    • It equals nil
    • It does not equal nil
    • The call does not compile
    • There will be a panic