go / intermediate
Snippet
Error Wrapping and Unwrapping
Go 1.13+ introduced error wrapping using the %w verb in fmt.Errorf. This allows you to add context to an error while still being able to check for the original sentinel error using errors.Is.
snippet.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package mainimport ("errors""fmt")var ErrNotFound = errors.New("not found")func fetchData() error {return fmt.Errorf("database error: %w", ErrNotFound)}func main() {err := fetchData()if err != nil {if errors.Is(err, ErrNotFound) {fmt.Println("Resource was not found")}fmt.Println("Original error:", err)fmt.Println("Unwrapped error:", errors.Unwrap(err))}}
Breakdown
1
fmt.Errorf("... %w", ErrNotFound)
Wraps the original error, preserving its identity for future checks.
2
errors.Is(err, ErrNotFound)
Recursively checks if any error in the chain matches the target error.
3
errors.Unwrap(err)
Returns the underlying error that was wrapped.