Errors · 3 MIN READ
%w adds context without hiding the cause
Wrap an error so callers can still match the original.
fmt.Errorf with %w produces an error that both reads well and still contains the original. errors.Is and errors.As walk that chain.
Two conventions make the chain readable: error strings are lowercase and unpunctuated because they get concatenated, and each layer adds only what it uniquely knows — usually the operation and its input.
SEE THE IDEA
Context can preserve the original cause
- 01
Cause
goerr := read()The original failure
- 02
Context
gofmt.Errorf("load: %w", err)Adds a message and an unwrap link
- 03
Caller
goerrors.Is(err, target)Can still recognize the cause
Wrapping links the new error to the old one instead of replacing its identity.
In practice
Wrap where you can add useful operation context, and avoid repeating the same information at every layer. The percent-v verb formats an error as text; percent-w wraps it for later inspection. Wrapping exposes the cause as part of your API, so decide whether callers should be allowed to depend on it.
Watch out
Only wrap a real non-nil error. A success path should return nil directly.
Work through the exercise
package main
import (
"errors"
"strconv"
)
var ErrNotANumber = errors.New("not a number")
// parsePort should report which input failed and still let callers
// match ErrNotANumber.
func parsePort(raw string) (int, error) {
n, err := strconv.Atoi(raw)
if err != nil {
return 0, ErrNotANumber
}
return n, nil
}
func main() {}Trace each value and write down your reasoning. Copy the source into GopherForge or your local Go environment to compile and check it. This web page does not execute your code or send it to a compiler service.
Progress stays in this browser. No account needed.