Error wrapping
Wrap errors when extra context helps callers and keep the original cause inspectable with `%w`.
Canonical guidance
- add context at boundaries where the operation name matters
- use
%wwhen callers may neederrors.Isorerrors.As - avoid wrapping mechanically when no new information is added
Use when
- I/O boundaries
- RPC or database calls
- translating low-level failures into higher-level operations
Avoid
- losing the original cause with
%v - wrapping the same error repeatedly with empty context
- exposing internal detail when the boundary should collapse it
Preferred pattern
func loadConfig(path string) error {
if err := readConfig(path); err != nil {
return fmt.Errorf("read config %q: %w", path, err)
}
return nil
}
Anti-pattern
- returning generic context strings that destroy the original error identity
Explanation: This anti-pattern is tempting because any formatted message looks clearer, but callers lose reliable inspection when the original error is no longer wrapped.
Why
- good wrapping keeps both human context and machine-readable cause chains
Related pages
Sources
- errors package - Go Team
- Working with Errors in Go 1.13 - Damien Neil and Jonathan Amsterdam
- Ignoring when to wrap an error (#49) - Teiva Harsanyi