go / intermediate
Snippet
Verifying Specific Error Chains with Errors Is
Standard equality comparison (`==`) fails when errors are wrapped. In Go, `errors.Is` traverses the error chain to check if any wrapped error matches a specific target error.
snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package mainimport ("errors""fmt")var ErrNotFound = errors.New("resource not found")func fetchResource() error {return fmt.Errorf("database query failed: %w", ErrNotFound)}func main() {err := fetchResource()if errors.Is(err, ErrNotFound) {fmt.Println("Handled: The resource indeed could not be found.")} else {fmt.Println("Error:", err)}}
Breakdown
1
var ErrNotFound = errors.New("resource not found")
Declares a sentinel error package variable representing a resource not found condition.
2
return fmt.Errorf("database query failed: %w", ErrNotFound)
Wraps the sentinel error using the %w formatting verb in fmt.Errorf to preserve the error chain.
3
if errors.Is(err, ErrNotFound) {
Recursively inspects the wrapped error chain to check if ErrNotFound is present.