Error Wrapping
Start with Error Wrapping
Wrapping records an error’s context while preserving the underlying cause for programmatic inspection.
What you’ll learn
- Explain the main purpose of error wrapping.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
Use fmt.Errorf("load profile: %w", err) to wrap the underlying error. The %w verb stores a cause accessible through the error-unwrapping protocol, while %v only formats the error text.
A caller can inspect the chain using errors.Is or errors.As. Add context at the appropriate boundary, but avoid repeating the same operation name at every layer.
Visualize how it works
Read the labels and compare the identities, types and storage relationships shown here.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import (
"errors"
"fmt"
)
var ErrMissing = errors.New("record missing")
func load() error { return fmt.Errorf("load user: %w", ErrMissing) }
func main() {
err := load()
fmt.Println("Message:", err)
fmt.Println("Cause matches:", errors.Is(err, ErrMissing))
}
Output
Message: load user: record missing
Cause matches: trueTrace what the program does
load wraps ErrMissing with the added context load user. The displayed message contains both descriptions, and errors.Is still recognizes the underlying sentinel error.
Avoid common mistakes
%vformats but does not wrap; use%wwhen the cause should remain inspectable.- Wrapping makes an underlying error observable as part of the API; consider which causes callers should depend on.
Try it yourself
Add a second wrapping function so the final message has two levels of context, then verify errors.Is still finds ErrMissing.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced Error Wrapping in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.