0PricingLogin
Go Academy · Lesson

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

  1. The error Interface
  2. Creating Custom Errors
  3. Error Wrapping and Unwrapping
  4. panic, recover and defer
← Back to Go Academy