errors.Is
- Version
- 1.27
- Since
- 1.13
- Review
- Draft
Summary#
Use errors.Is when callers need to recognize a sentinel error even after another function wraps it with context.
Syntax#
if errors.Is(err, ErrUnavailable) {
// Handle the known condition.
}
Example#
package main
import (
"errors"
"fmt"
)
var errUnavailable = errors.New("unavailable")
func main() {
err := fmt.Errorf("open cache: %w", errUnavailable)
fmt.Println(err == errUnavailable)
fmt.Println(errors.Is(err, errUnavailable))
}
Expected output#
false
true
Common mistakes#
Comparing error messages is brittle. Pass a comparable sentinel as the target. Use %w when wrapping with fmt.Errorf so the original error remains in the error tree. %v only formats its message.
Version applicability#
Introduced in Go 1.13 with standard error wrapping. On earlier Go versions, wrapper APIs provided their own way to inspect a cause.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0