Go errors.Is and fmt.Errorf
errors.Is checks an error and its wrapped causes for a match. The %w verb in fmt.Errorf preserves the underlying error for inspection.
A simple example
errors.Is and fmt.Errorf
- Start with An error wrapped with a note
- Do this Check for the original error
- Result Match
Syntax
errors.Is(err, target)
Run this example in Go
Save the program as main.go. Use Go 1.21 or later.
go run main.go
Recognize a wrapped lookup error
A batch processor must distinguish an anticipated input problem from a different failure. Examine the operation's error information before deciding whether to skip one record, report the cause or stop.
package main
import (
"errors"
"fmt"
)
func main() {
missing := errors.New("missing item")
err := fmt.Errorf("catalog lookup: %w", missing)
fmt.Println(errors.Is(err, missing))
fmt.Println(errors.Is(err, errors.New("missing item")))
}
true false
Two errors constructed separately can have identical text and different identities. Wrap a shared sentinel to preserve the meaning across application layers.
Go documentation for errors.Is and fmt.Errorf
Read a saved shift record
The closing clerk saved the file before leaving. Open the expected file and show the desk whether it is available.
Handle an unsubmitted handover
The next shift opens an empty inbox before the first clerk submits a file. Open the expected file and show the desk whether it is available.