Wrap and match with errors.Is
Wrap and match with errors.Is
Wrapping an error adds context while preserving its underlying error for inspection. Use fmt.Errorf with %w and an error operand. errors.Is checks the error itself and wrapped errors for a match, including custom Is methods. A sentinel is a stable error value used to identify a known condition.
package main
import ( "errors" "fmt")
var ErrMissing = errors.New("missing")
func main() { err := fmt.Errorf("load record: %w", ErrMissing) fmt.Println(err) fmt.Println(err == ErrMissing, errors.Is(err, ErrMissing))}Direct equality misses the wrapper. errors.Is traverses it and finds ErrMissing. Use a comparable target error. Only wrap a non-nil error when propagating failure; fmt.Errorf with a nil operand does not simply return nil.
Expected output:
load record: missingfalse trueCompare %w with %v
package main
import ( "errors" "fmt")
var ErrBusy = errors.New("busy")
func main() { a := fmt.Errorf("save: %w", ErrBusy) b := fmt.Errorf("save: %v", ErrBusy) fmt.Println(a.Error() == b.Error()) fmt.Println(errors.Is(a, ErrBusy), errors.Is(b, ErrBusy)) fmt.Println(errors.Unwrap(a) == ErrBusy)}The displayed text is identical, but only %w exposes the underlying error. errors.Unwrap returns a single wrapped error when the error has Unwrap() error. Wrapping makes underlying details observable to callers; choose it deliberately.
Expected output:
truetrue falsetrueTry it locally
Define ErrClosed and wrap it twice using %w with contexts "read" and "request". Print whether errors.Is finds ErrClosed.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Errors and cleanup 03: Wrap and match with errors.Is
Check the lesson objective before moving on.
Which formatting verb preserves an error for unwrapping?
Which checks for a sentinel through wrappers?