Error comparison
Compare errors with `errors.Is` and `errors.As` when wrapping may be involved; direct equality and brittle type checks fail easily.
Canonical guidance
- use
errors.Isfor sentinel-style comparisons - use
errors.Asto find a specific error type in a chain - compare directly only when no wrapping or abstraction boundary is involved
Use when
- wrapped errors
- retry classification
- typed error metadata
Avoid
err == targetthrough wrapper boundaries- type assertions against only the outermost error
- mixing many comparison styles without reason
Preferred pattern
if errors.Is(err, context.DeadlineExceeded) {
return retryLater()
}
var pathErr *fs.PathError
if errors.As(err, &pathErr) {
log.Printf("path failed: %s", pathErr.Path)
}
Anti-pattern
- checking only concrete wrapper types and missing the real cause underneath
Explanation: This anti-pattern is tempting because direct equality and type assertions are simple, but they break as soon as wrapping enters the picture.
Why
- robust comparison should survive context-rich error propagation
Related pages
Sources
- errors package - Go Team
- Working with Errors in Go 1.13 - Damien Neil and Jonathan Amsterdam
- Error comparison pitfalls (#50-51) - Teiva Harsanyi