errors.Join
Use `errors.Join` when multiple sibling failures matter and callers still need `errors.Is` and `errors.As` to work.
Canonical guidance
- use
errors.Joinwhen multiple sibling failures deserve to survive - keep joined causes inspectable with
errors.Isanderrors.As - prefer a single wrapped error when there is one dominant cause
Use when
- cleanup steps that can each fail
- fan-out work reporting multiple relevant failures
- validation collecting several independent problems
Avoid
- joining errors mechanically because a slice exists
- flattening all context into one opaque string
- assuming the display order is an API contract
Preferred pattern
if err1 != nil || err2 != nil {
return errors.Join(err1, err2)
}
return nil
Anti-pattern
- concatenating several error strings into one message and discarding machine-readable causes
Explanation: This anti-pattern is tempting because it is quick, but callers lose structured inspection.
Why
errors.Joinpreserves multiple causes without giving up the normal Go error inspection APIs
Related pages
Sources
- errors package - Go Team