Wrapping errors with %w

An error is an interface with one method, Error() string, so the only thing a caller can do with an arbitrary error is print it. Wrapping adds a layer with more text and keeps the cause underneath: fmt.Errorf("load user %d: %w", id, err) returns an error that prints the new context and still holds the old one. The errors lesson introduced the value; this one builds the chain.

A message with a cause

%w is the verb that remembers: it returns a wrapper whose Unwrap gives back the original error. errors.Unwrap returns that original or nil, and a loop of it walks the whole chain. The wrapper is not a sentinel and cannot be compared with ==, which is why the next lesson uses errors.Is instead.

package main import ( "errors" "fmt" ) var ErrNotFound = errors.New("not found") func load(id int) error { if id <= 0 { return fmt.Errorf("load user %d: %w", id, ErrNotFound) } return nil } func main() { err := load(0) fmt.Println(err) inner := errors.Unwrap(err) fmt.Println("unwrapped:", inner) fmt.Println("same as the sentinel:", inner == ErrNotFound) fmt.Println("nothing under the sentinel:", errors.Unwrap(inner)) }

go run wrap.go

load user 0: not found
unwrapped: not found
same as the sentinel: true
nothing under the sentinel: <nil>

The printed line has the context first and the cause last, and the unwrap returned exactly the sentinel that was wrapped, so == worked at that depth. Under the sentinel the chain ended: a sentinel made by errors.New has nothing below it.

A custom error that unwraps

A struct error can carry fields and a cause at once, which is what a layered program needs: the query text for the log, the underlying error for the decision. Implementing Unwrap() error puts the type into the chain, and errors.Is and errors.As then reach through it.

package main import ( "errors" "fmt" ) type QueryError struct { Query string Err error } func (e *QueryError) Error() string { return "query " + e.Query + ": " + e.Err.Error() } func (e *QueryError) Unwrap() error { return e.Err } var ErrTimeout = errors.New("timeout") func main() { err := fmt.Errorf("handler: %w", &QueryError{Query: "select 1", Err: ErrTimeout}) fmt.Println(err) for e := err; e != nil; e = errors.Unwrap(e) { fmt.Printf("%T: %v\n", e, e) } }

go run custom.go

handler: query select 1: timeout
*fmt.wrapError: handler: query select 1: timeout
*main.QueryError: query select 1: timeout
*errors.errorString: timeout

The loop printed the wrapper, the query error and the timeout: three types, three layers, one error value. The %T verb showed the pointer type at each step, which is the shape errors.As looks for when it searches the chain for a type.

Wrap or decorate?

%v copies the text of the cause and drops the value, so the line reads the same and the chain is gone. That is the right choice at a boundary where the cause is an implementation detail, and the wrong one when the caller must still recognise the error. The rule of thumb: %w when the caller may test or inspect, %v when the only consumer is a human reading a log.

package main import ( "errors" "fmt" ) var ErrDenied = errors.New("denied") func main() { wrapped := fmt.Errorf("open file: %w", ErrDenied) decorated := fmt.Errorf("open file: %v", ErrDenied) fmt.Println("wrapped:", wrapped) fmt.Println("decorated:", decorated) fmt.Println("unwrap wrapped:", errors.Unwrap(wrapped) == ErrDenied) fmt.Println("unwrap decorated:", errors.Unwrap(decorated)) }

go run decorate.go

wrapped: open file: denied
decorated: open file: denied
unwrap wrapped: true
unwrap decorated: <nil>

Both errors printed identically and only one survived Unwrap. A function that returns fmt.Errorf("...: %v", err) from a library is silently removing the contract its callers were promised.

Two causes in one error

Since Go 1.20 an error can wrap more than one cause: two %w verbs in one fmt.Errorf produce an error whose Unwrap returns []error, and errors.Is finds either. errors.Join builds the same shape from a list, which is what a cleanup routine needs when two things failed at once.

package main import ( "errors" "fmt" ) var ( ErrDisk = errors.New("disk full") ErrQuota = errors.New("quota exceeded") ) func main() { err := fmt.Errorf("upload failed: %w; %w", ErrDisk, ErrQuota) fmt.Println(err) fmt.Println("disk:", errors.Is(err, ErrDisk)) fmt.Println("quota:", errors.Is(err, ErrQuota)) joined := errors.Join(ErrDisk, ErrQuota) fmt.Println("joined is multi:") fmt.Println(joined) }

go run multi.go

upload failed: disk full; quota exceeded
disk: true
quota: true
joined is multi:
disk full
quota exceeded

The joined error prints one line per cause and errors.Is matched both sentinels. A chain with two branches is not a tree a program should build by hand; the two-cause form exists so that a function that tried two things can report both without inventing a message.

Unwrap is not on the error interface

The error interface has only Error, so a value of that type has no Unwrap to call: the wrapping functions and errors.Unwrap look for the method on the dynamic type. That is why the chain is walked with a package function and not with a method on the interface.

package main import "fmt" func main() { var err error fmt.Println(err.Unwrap()) }

go build -o method method.go

# command-line-arguments
./method.go:7:18: err.Unwrap undefined (type error has no field or method Unwrap)

The message is about the static type, which is what the compiler sees. A custom error that needs to be unwrapped declares the method on its own type, and a caller that wants it uses errors.As rather than a direct call.

Exercises

  1. Wrap the same sentinel three times with different contexts and print the chain with a loop. How many layers does errors.Unwrap report?
  2. Write a ValidationError that holds a field name and a cause, and make it unwrap. Print it once with %v and once with %+v of the struct.
  3. Replace a %v in a library return with %w and write the one-line test that fails before the change and passes after it.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does %w do in fmt.Errorf?

    Answer

    Wraps the error so Unwrap can return it

    %w stores the cause in the wrapper; %v only copies its text.

  2. What does this program print? package main import ( "errors" "fmt" ) var ErrNotFound = errors.New("not found") func load(id int) error { if id <= 0 { return fmt.Errorf("load user %d: %w", id, ErrNotFound) } return nil } func main() { err := load(0) fmt.Println(err) inner := errors.Unwrap(err) fmt.Println("unwrapped:", inner) fmt.Println("same as the sentinel:", inner == ErrNotFound) fmt.Println("nothing under the sentinel:", errors.Unwrap(inner)) }

    Answer

    load user 0: not found / unwrapped: not found / same as the sentinel: true / nothing under the sentinel: <nil>

    The wrapper prints the context and the sentinel, Unwrap returns the sentinel itself, and a sentinel has no cause.

  3. What does errors.Unwrap return for an error that was not wrapped?

    Answer

    nil

    Only a wrapper has a cause; a plain errors.New value returns nil.

  4. How many lines does the loop print? package main import ( "errors" "fmt" ) type QueryError struct { Query string Err error } func (e *QueryError) Error() string { return "query " + e.Query + ": " + e.Err.Error() } func (e *QueryError) Unwrap() error { return e.Err } var ErrTimeout = errors.New("timeout") func main() { err := fmt.Errorf("handler: %w", &QueryError{Query: "select 1", Err: ErrTimeout}) fmt.Println(err) for e := err; e != nil; e = errors.Unwrap(e) { fmt.Printf("%T: %v\n", e, e) } }

    Answer

    handler: query select 1: timeout / *fmt.wrapError: handler: query select 1: timeout / *main.QueryError: query select 1: timeout / *errors.errorString: timeout

    The chain has three layers, one for each fmt.Errorf or Unwrap on the way down.

  5. When is %v the right verb for an error?

    Answer

    When the cause is an implementation detail the caller should not test

    %v decorates the text and breaks the chain on purpose.

  6. What does the last line of this program print? package main import ( "errors" "fmt" ) var ErrDenied = errors.New("denied") func main() { wrapped := fmt.Errorf("open file: %w", ErrDenied) decorated := fmt.Errorf("open file: %v", ErrDenied) fmt.Println("wrapped:", wrapped) fmt.Println("decorated:", decorated) fmt.Println("unwrap wrapped:", errors.Unwrap(wrapped) == ErrDenied) fmt.Println("unwrap decorated:", errors.Unwrap(decorated)) }

    Answer

    wrapped: open file: denied / decorated: open file: denied / unwrap wrapped: true / unwrap decorated: <nil>

    The %v version has no cause, so Unwrap finds nothing.

  7. What does an error with two %w verbs give to Unwrap?

    Answer

    A slice of two errors

    Since Go 1.20 a multi-cause error returns []error from Unwrap, and errors.Is checks every branch.

  8. What do the two errors.Is lines print? package main import ( "errors" "fmt" ) var ( ErrDisk = errors.New("disk full") ErrQuota = errors.New("quota exceeded") ) func main() { err := fmt.Errorf("upload failed: %w; %w", ErrDisk, ErrQuota) fmt.Println(err) fmt.Println("disk:", errors.Is(err, ErrDisk)) fmt.Println("quota:", errors.Is(err, ErrQuota)) joined := errors.Join(ErrDisk, ErrQuota) fmt.Println("joined is multi:") fmt.Println(joined) }

    Answer

    upload failed: disk full; quota exceeded / disk: true / quota: true / joined is multi: / disk full / quota exceeded

    Both sentinels are in the chain, so Is finds each of them.

  9. What does the compiler say about this program? package main import "fmt" func main() { var err error fmt.Println(err.Unwrap()) }

    Answer

    error has no field or method Unwrap)

    The error interface declares only Error, so Unwrap is not in its method set.

  10. Which function walks a chain without knowing its types?

    Answer

    errors.Unwrap

    errors.Unwrap reads the optional method from the dynamic type, which the interface does not expose.

The code on this page was run with go 1.26.10 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev

Banner image