One Missing %w and errors.Is Stops Working
This bug won't show up in code review, won't fail a build and won't trip go vet. It only appears in production, and only on the one code path nobody bothered to write a test for: the error path.
var ErrNotFound = errors.New("resource not found")
func fetchFromDB(id string) error {
return fmt.Errorf("fetching id %s: %w", id, ErrNotFound)
}
func loadResource(id string) error {
if err := fetchFromDB(id); err != nil {
return fmt.Errorf("loading resource: %v", err) // note: %v, not %w
}
return nil
}
func handleRequest(id string) int {
err := loadResource(id)
if errors.Is(err, ErrNotFound) {
return http.StatusNotFound
}
if err != nil {
return http.StatusInternalServerError
}
return http.StatusOK
}
Run this and every request for a missing resource returns 500 instead of 404. The message in the log still reads "loading resource: fetching id abc123: resource not found", so at a glance everything looks fine.
Someone reading the log sees the right sentence. The programme reading the error chain sees a dead end.
%w keeps the error's identity, %v keeps only its words
Both verbs accept an error as an argument, and both produce the same formatted string. The difference never shows in the output; it's all in the plumbing:
%wtellsfmt.Errorfto make the resulting error implementUnwrap() error, returning the wrapped value.%vjust calls the wrapped error'sError()method and throws the value away.
So the string survives and the identity does not.
errors.Is and errors.As both work by walking that Unwrap chain. Quick detour into the standard library, because seeing the loop makes the failure obvious. Simplified, errors.Is looks like this:
func Is(err, target error) bool {
for {
if err == target {
return true
}
if x, ok := err.(interface{ Is(error) bool }); ok && x.Is(target) {
return true
}
unwrapper, ok := err.(interface{ Unwrap() error })
if !ok {
return false
}
err = unwrapper.Unwrap()
if err == nil {
return false
}
}
}
As soon as one link in the chain fails to implement Unwrap(), the loop stops and returns false, whatever is buried further down.
ErrNotFound really is in that error's string representation, but the walk never gets there: the error returned by loadResource has nothing to unwrap into. It's a dead-end node dressed up as a chain.
go vet can't tell a print from a propagate
go vet's printf checker does catch some kinds of %w misuse:
- Using
%wwith an argument that doesn't implementerror("Errorf format %w has arg ... which does not implement error"). - Using more than one
%win a single format string, before Go 1.20 made that legal.
It can't catch the mistake above, because %v is a perfectly legal, ordinary verb for an error argument. Every error implements Error() string, and %v on anything with an Error() method just calls it.
Nothing about fmt.Errorf("loading resource: %v", err) is type-incorrect. It's as valid as printing an error to a log line, because that's all it is.
The compiler has no way to know you meant "propagate this error's identity" rather than "print this error's message". Both are common, legitimate things to do with an error value, and only you know which one you meant at that call site.
This is the uncomfortable bit: there's no type error, nil pointer or race here. The bug is a one-character difference between two equally valid, idiomatic pieces of code, and only one of them preserves a property (identity through the chain) that nothing in the type system enforces.
The fix isn't vigilance, it's a linter
Telling people to "be careful" about which verb they use is wishful thinking. The practical answer is errorlint, a static analysis tool built for exactly this class of mistake.
Its core check, sometimes called the "non-wrapping format verb" check, flags this pattern: a call to fmt.Errorf where one of the arguments is a value of type error but the matching verb is %v or %s instead of %w. Running it against the snippet above produces something like:
main.go:12:39: non-wrapping format verb for fmt.Errorf. Use `%w` to format errors
errorlint also checks the other direction: comparisons like err == ErrNotFound and type switches on error values. Those compile, and look identical to the correct errors.Is/errors.As form, yet silently stop working the moment something upstream starts wrapping that error.
If your CI doesn't run it, this whole category of bug is invisible until someone hits the affected path in production and starts wondering why a 404 became a 500.
Multiple wraps give the same mistake more places to hide
Go 1.20 added support for multiple %w verbs in a single fmt.Errorf call, alongside errors.Join. The resulting error implements Unwrap() []error rather than the single-error form, and both errors.Is and errors.As were updated to walk a tree instead of a list, checking every branch:
err := fmt.Errorf("saving record: %w and %w", ErrValidation, ErrPermission)
errors.Is(err, ErrValidation) // true
errors.Is(err, ErrPermission) // true
That's a real improvement when an operation can fail for more than one underlying reason at once. The basic problem is unchanged, though, and now the same mistake has more places to hide.
Forget %w on one of three joined errors in a long fmt.Errorf call and you get a chain that correctly reports two of the three failures to errors.Is and silently drops the third. That's harder to spot than the single-verb version, because two out of three checks pass and the code looks like it's doing the right thing.
A boundary test costs less than the incident
Alongside errorlint in CI, the cheap insurance is a test at whichever boundary decides your application's behaviour. That's usually the outermost layer, the one that maps an error to a decision (an HTTP status, a retry, an alert). Something as blunt as this:
func TestLoadResource_NotFoundIsDetectable(t *testing.T) {
err := loadResource("missing-id")
if !errors.Is(err, ErrNotFound) {
t.Fatalf("expected errors.Is to detect ErrNotFound, got: %v", err)
}
}
That would have caught the original bug immediately, and it costs about as much to write as the mistake did to introduce.
A general "test your error handling" instruction is vague; this test checks one specific property. It doesn't ask whether the function returns an error. It asks whether the identity of a specific sentinel survives the trip through every layer that's supposed to preserve it.
That's the property %v quietly breaks, and it's the one thing a log line reading "resource not found" will never tell you has gone wrong.