Error Wrapping and Unwrapping
Using %w, errors.Is, and errors.As
What Is Error Wrapping?
Error wrapping embeds an original error inside a new error, preserving the original for programmatic inspection while adding context. Introduced properly in Go 1.13:
package main
import ("fmt"; "errors")
var ErrDB = errors.New("database unreachable")
func queryUsers() error {
return fmt.Errorf("queryUsers: %w", ErrDB)
}
func loadProfile(id int) error {
return fmt.Errorf("loadProfile(%d): %w", id, queryUsers())
}
func main() {
err := loadProfile(42)
fmt.Println(err) // loadProfile(42): queryUsers: database unreachable
}The %w Verb
Use %w (not %v) in fmt.Errorf to wrap an error. The wrapped error is accessible via errors.Unwrap:
package main
import ("fmt"; "errors")
func main() {
inner := errors.New("inner error")
outer := fmt.Errorf("outer: %w", inner)
fmt.Println(outer) // outer: inner error
fmt.Println(errors.Unwrap(outer)) // inner error
fmt.Println(errors.Is(outer, inner)) // true
}All lessons in this course
- The error Interface
- Creating Custom Errors
- Error Wrapping and Unwrapping
- panic, recover and defer