Go core
Browse topics

Wrapping errors with %w

Version
1.27
Since
1.13
Review
Draft

Summary#

fmt.Errorf with %w adds context and keeps the cause reachable. errors.Unwrap returns one layer from an error with an Unwrap() error method. %v copies only the message.

Syntax#

go
return fmt.Errorf("load profile %d: %w", id, err)
cause := errors.Unwrap(wrapped)

Example#

go
package main

import (
	"errors"
	"fmt"
)

func main() {
	cause := errors.New("permission denied")
	query := fmt.Errorf("query users: %w", cause)
	request := fmt.Errorf("load profile: %w", query)

	fmt.Println(request)
	for err := request; err != nil; err = errors.Unwrap(err) {
		fmt.Println("-", err)
	}

	opaque := fmt.Errorf("load profile: %v", query)
	fmt.Println(errors.Unwrap(opaque) == nil)
}

Expected output#

Text
load profile: query users: permission denied
- load profile: query users: permission denied
- query users: permission denied
- permission denied
true

Common mistakes#

fmt.Errorf("save: %w", err) returns a non-nil error even when err is nil. Wrap only after checking if err != nil. Wrapping also lets callers depend on the cause, so use %v when the cause is an internal detail.

Version applicability#

Go 1.13 added %w and errors.Unwrap. Go 1.20 allows several %w verbs in one call. The result then has an Unwrap() []error method, for which errors.Unwrap returns nil.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0