liveBook · Manning

%w error verb

As explained in 100 Go Mistakes and How to Avoid Them

The %w directive is a Go fmt formatting directive that records an operand as the underlying error of a returned formatted error.

The %w directive wraps an existing error while preserving the original error for later inspection. It is useful when adding context, marking an error, or doing both. section 7.2

Add context without losing the cause

if err != nil { return fmt.Errorf("bar failed: %w", err) } Unlike %v, which formats the error message and discards the source-error relationship, %w keeps the wrapped error available to callers. section 7.2

Wrapping also changes how callers must check errors. A direct type switch sees only the outer formatted error, so a refactoring that adds %w can make an existing type check fail. Use errors.As to find a wrapped error type and errors.Is to compare a wrapped error value. section 7.3 section 7.8

Preserve transient-error handling

if err != nil { return 0, fmt.Errorf("failed to get transaction %s: %w", transactionID, err) } if errors.As(err, &transientError{}) { http.Error(w, err.Error(), http.StatusServiceUnavailable) } else { http.Error(w, err.Error(), http.StatusBadRequest) } section 7.3

Use %w when callers should retain access to the cause; return the error directly when no context or classification is needed. Avoid wrapping when exposing the source error would create unwanted coupling. section 7.2 section 7.8

if err != nil {
    return fmt.Errorf("bar failed: %w", err)
}

Inspect the compact implementation of contextual error wrapping with fmt.Errorf and %w. section 7.2

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Explains wrapping, contrasts %w with %v, and traces why errors.As replaces direct type checks after refactoring.
Examples
Uses bar failure context, permission errors, transient database failures, and HTTP 400-versus-503 responses.
What it assumes
Assumes basic Go error returns and introduces wrapping, source-error availability, and errors.As or errors.Is checks.
What you can do after
Diagnose/debug with it by preserving causes, selecting %w or %v, and checking wrapped errors accurately.
How it connects
Connects error wrapping with fmt.Errorf, errors.As, errors.Is, error sentinels, error types, and HTTP status handling.

Also explained in

Compare how 2 books explain %w error verb →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Go Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.