fmt.Errorf and %w
fmt.Errorf("load config: %w", err) builds a new error whose message includes context and whose cause is err. errors.Is and errors.As walk that chain. %w is the verb that preserves the cause.
Detailed Explanation
A low-level call returns open go.mod: no such file. A mid-level function should not pass that up unchanged: the operator needs to know what you were doing. Wrapping adds that sentence and keeps the original error as a value, not only as text.
%w is the wrap. fmt.Errorf("load config: %w", err) implements Unwrap() error on the result. errors.Is(err, fs.ErrNotExist) then returns true if any link in the chain matches. errors.As finds a concrete type in the chain. One %w per Errorf is the rule; two %w verbs in one format string is a compile-time error in current Go (it was a runtime surprise before).
%v and %s do not wrap. fmt.Errorf("load config: %v", err) copies the string and drops the type. errors.Is will not see fs.ErrNotExist. Use %v only when you intend to hide the cause, which is rare.
errors.Join combines siblings. When several failures happen (flush this, close that), errors.Join(err1, err2) builds an error that unwraps to a list. errors.Is still walks them. Prefer Join over concatenating strings when both errors matter.
errors.Unwrap is rarely called directly. Use Is and As. They handle sentinels, types, and joined errors. A manual loop over Unwrap misses Join and custom multi-error types.
Where to wrap. Once per layer is enough: return fmt.Errorf("parse listen addr %q: %w", raw, err). Wrapping again in the next function with a new prefix is fine. Wrapping with the same prefix twice produces a stutter in logs. Do not wrap at the top of main only to log: log.Fatal(err) is enough if every layer already added context.
What it costs. Each wrap is a small allocation and a longer Error() string. That is cheap next to an I/O failure. The cost of not wrapping is an operator who sees EOF and no file name.
Code Examples
package main
import (
"errors"
"fmt"
"io/fs"
"os"
)
func load(path string) error {
_, err := os.ReadFile(path)
if err != nil {
return fmt.Errorf("load config %s: %w", path, err)
}
return nil
}
func main() {
err := load("missing.toml")
fmt.Println(err)
fmt.Println(errors.Is(err, fs.ErrNotExist)) // true
}func both(a, b error) error {
if a == nil {
return b
}
if b == nil {
return a
}
return errors.Join(a, b)
}func hide(err error) error {
// String only: Is will not see the cause.
return fmt.Errorf("operation failed: %v", err)
}Common Gotchas
More than one `%w` in a single `Errorf` is invalid
join first, or wrap in two steps.
`%v` looks wrapped in the log and is not
`errors.Is` fails. Use `%w` when the caller might inspect the cause.
Wrapping a nil error
`fmt.Errorf("x: %w", nil)` produces a non-nil error whose unwrap is nil. Check `err` before wrapping.
`fmt.Errorf` with no `%w` is the same family as `errors.New`
a leaf error with a formatted message.