Error Wrapping & Inspection

Error Wrapping & Inspection in Go: A parcel leaves a warehouse with one barcode on it. At each depot along the route, a clerk slaps a new label on the outside…

The Analogy: The Parcel That Collects Shipping Labels

A parcel leaves a warehouse with one barcode on it. At each depot along the route, a clerk slaps a new label on the outside -- received at Leeds, loaded on van 12, attempted delivery -- and crucially nobody peels off the labels underneath. When the parcel finally comes back marked "undeliverable", you can read the whole route off the outside of the box, in order, and customs can still scan the original barcode buried under four layers.

That is %w. fmt.Errorf("load config: %w", err) adds one label. The message reads outermost-first, so a fully labelled error like checkout: submit order 4471: charge account: no quota is a path from the API surface down to the actual cause -- and the cause is still there as a value, not as a substring. errors.Is scans every label for a barcode you name; errors.As scans for a form of a particular shape and hands it to you filled in; errors.Unwrap peels exactly one layer.

Which label to add is a judgement call with a simple rule: add the one noun this layer knows and nothing else. The storage layer knows the key; the service layer knows the operation; the handler knows the request. If every layer adds only what its neighbours could not have known, the finished message reads like a route. If layers repeat each other, you get failed to save: error saving user: save failed: no quota, which is four labels saying one thing.

Where the analogy stops: labels are an API commitment. The moment you wrap a sentinel with %w, callers may legitimately write errors.Is(err, ErrNoQuota), and quietly switching to %v later breaks them with no compile error. That cuts both ways -- %v is the deliberate choice when the inner error is an implementation detail you refuse to promise, and severing the chain on purpose is a design decision, not an oversight. And since errors.Join, the chain is really a tree: Is and As do a depth-first search over branches, not a walk down a list.


Syntax or Core Structure

package main

import (
	"errors"
	"fmt"
	"io/fs"
	"os"
	"strconv"
)

var ErrNoQuota = errors.New("no quota")

// A wrapper type: Error() formats, Unwrap() exposes the cause.
type StageError struct {
	Stage string
	Err   error
}

func (e *StageError) Error() string { return e.Stage + ": " + e.Err.Error() }
func (e *StageError) Unwrap() error { return e.Err }

func main() {
	l1 := fmt.Errorf("charge account: %w", ErrNoQuota)
	l2 := fmt.Errorf("submit order 4471: %w", l1)
	l3 := &StageError{Stage: "checkout", Err: l2}

	fmt.Println(l3)
	fmt.Println("peel 1:", errors.Unwrap(l3))
	fmt.Println("peel 2:", errors.Unwrap(errors.Unwrap(l3)))
	fmt.Println("is ErrNoQuota:", errors.Is(l3, ErrNoQuota))

	var se *StageError
	fmt.Println("as StageError:", errors.As(l3, &se))
	fmt.Println("stage:", se.Stage)

	// %v severs the chain on purpose: the message survives, the value does not.
	opaque := fmt.Errorf("checkout: %v", l2)
	fmt.Println("severed:", errors.Is(opaque, ErrNoQuota))

	// Standard library chains: *fs.PathError wrapping a syscall error.
	_, err := os.Open("no-such-file-here.txt")
	fmt.Println("is fs.ErrNotExist:", errors.Is(err, fs.ErrNotExist))
	var pe *fs.PathError
	if errors.As(err, &pe) {
		fmt.Printf("op=%s path=%s\n", pe.Op, pe.Path)
	}

	// strconv hides its sentinels inside *strconv.NumError.
	_, nerr := strconv.Atoi("12x")
	fmt.Println("is strconv.ErrSyntax:", errors.Is(nerr, strconv.ErrSyntax))
	var ne *strconv.NumError
	if errors.As(nerr, &ne) {
		fmt.Printf("func=%s num=%q\n", ne.Func, ne.Num)
	}
}

Output:

checkout: submit order 4471: charge account: no quota
peel 1: submit order 4471: charge account: no quota
peel 2: charge account: no quota
is ErrNoQuota: true
as StageError: true
stage: checkout
severed: false
is fs.ErrNotExist: true
op=open path=no-such-file-here.txt
is strconv.ErrSyntax: true
func=Atoi num="12x"

The last two blocks are the point of the whole lesson: you never have to guess at a standard-library error. os.Open returns a *fs.PathError that both errors.Is and errors.As can interrogate, so you can branch on fs.ErrNotExist and read the exact path. The platform-specific text underneath -- which differs between operating systems -- is never something you need to match on.


Technical Depth: How the Chain Is Built and Walked

%w, %v and the shape of what you get back

fmt.Errorf inspects your verbs. With no %w, it returns a plain error with no Unwrap method at all. With exactly one %w it returns an internal *fmt.wrapError carrying Unwrap() error. With two or more %w verbs -- legal since Go 1.20 -- it returns a *fmt.wrapErrors carrying Unwrap() []error, which turns the chain into a tree at that node.

You writeUnwrap methoderrors.Is reaches the causeUse when
fmt.Errorf("ctx: %w", err)Unwrap() errorYesThe cause is part of your contract
fmt.Errorf("ctx: %v", err)noneNoThe cause is a private implementation detail
fmt.Errorf("%w and %w", a, b)Unwrap() []errorYes, both branchesTwo independent causes, one message
errors.Join(a, b, nil)Unwrap() []errorYes, nils droppedAccumulating unrelated failures
errors.New("ctx: " + err.Error())noneNoAlmost never -- prefer %v

One trap has no good failure mode: fmt.Errorf("ctx: %w", nil) does not produce nil. fmt sees an operand that is not an error, prints ctx: %!w(<nil>), and hands back a perfectly non-nil error with no Unwrap. Every wrap belongs inside an if err != nil.

The algorithms, exactly

errors.Is(err, target) walks the tree. At each node it first checks node == target -- a plain interface comparison, which is why sentinels must be comparable pointer values from errors.New and never structs holding a slice. Then, if the node has a method Is(error) bool, it calls it and returns true if that says so. Then it descends: Unwrap() error gives one child, Unwrap() []error gives several and each subtree is searched depth-first, left to right.

errors.As(err, target) walks the same tree, but at each node asks whether the node is assignable to *target's element type; if so it assigns and stops. A node with an As(any) bool method gets to answer for itself. target must be a non-nil pointer to either a type implementing error or an interface -- anything else panics, which is a deliberate design choice: it is a programming error, not a runtime condition.

Teaching Is and As new tricks

Both methods let a type match things it is not:

var ErrClientFault = errors.New("client fault")

type httpError struct {
	Status int
	Err    error
}

func (e *httpError) Error() string { return fmt.Sprintf("http %d: %v", e.Status, e.Err) }
func (e *httpError) Unwrap() error { return e.Err }

// Any 4xx now satisfies errors.Is(err, ErrClientFault).
func (e *httpError) Is(target error) bool {
	return target == ErrClientFault && e.Status >= 400 && e.Status < 500
}

That converts a numeric range into a single named condition callers can test without importing your status constants. Keep such methods pure and cheap -- Is may be called several times per node during a search.

What each layer should add

LayerKnowsGood labelBad label
Storagekey, operationstore get "u9"database error
Servicebusiness operationlink u9failed to link
Handlerrequest, userPOST /linksinternal error occurred

Three rules fall out. Never start a wrap with "failed to" or "error" -- the word error already appears in every log line that prints one. Never wrap at the origin: errors.New and a custom type already carry their own context. And never wrap twice in one function, which is what happens when you wrap an error and also return it through a helper that wraps.

When not to wrap at all

Wrapping leaks. If your package is a public API and the inner error comes from your database driver, %w promises callers they may match on driver types forever -- switching from PostgreSQL to SQLite then becomes a breaking change. Map to your own sentinel instead. The same applies in reverse for cancellation: wrapping context.Canceled in a layer that treats it as a real failure produces errors that look retryable and are not, so classify it before it becomes a cause.

There are no stack traces

Standard-library errors carry no stack, and %+v on a wrapped error is identical to %v -- the extra flag is passed down to whatever formats the leaf, and errors.New ignores it. This is intentional: a wrapping chain built with one noun per layer names the logical path, which is more useful in production logs than 40 frames of runtime internals. If you genuinely need frames, capture runtime.Callers in your own error type and expose it through a method, or use a third-party package -- but do not add it to every layer, or you will pay for a stack capture on hot error paths like "cache miss".


Real World Example: Three Layers, One Readable Route

An alias service: storage, a service operation, and a transport layer that maps error classes to status codes. Each layer adds exactly one noun, and the handler never once looks at a message string.

package main

import (
	"errors"
	"fmt"
	"strings"
)

// ---------- domain vocabulary ----------
var (
	ErrNotFound    = errors.New("not found")
	ErrConflict    = errors.New("conflict")
	ErrInvalid     = errors.New("invalid input")
	ErrClientFault = errors.New("client fault")
)

// ---------- storage layer: knows the key and the operation ----------
type storeError struct {
	Op  string
	Key string
	Err error
}

func (e *storeError) Error() string {
	return fmt.Sprintf("store %s %q: %v", e.Op, e.Key, e.Err)
}
func (e *storeError) Unwrap() error { return e.Err }

var rows = map[string]string{"u1": "ada", "u2": "grace"}

func fetch(key string) (string, error) {
	if key == "" {
		return "", &storeError{"get", key, errors.New("empty key")}
	}
	v, ok := rows[key]
	if !ok {
		return "", &storeError{"get", key, ErrNotFound}
	}
	return v, nil
}

func insert(key, val string) error {
	if _, exists := rows[key]; exists {
		return &storeError{"put", key, ErrConflict}
	}
	rows[key] = val
	return nil
}

// ---------- service layer: knows the business operation ----------
func link(key, alias string) error {
	if strings.TrimSpace(alias) == "" {
		return fmt.Errorf("link %s: %w", key, ErrInvalid)
	}
	if _, err := fetch(key); err != nil {
		return fmt.Errorf("link %s: %w", key, err)
	}
	if err := insert(alias, key); err != nil {
		return fmt.Errorf("link %s: %w", key, err)
	}
	return nil
}

// ---------- transport layer: knows the response ----------
type httpError struct {
	Status int
	Err    error
}

func (e *httpError) Error() string { return fmt.Sprintf("http %d: %v", e.Status, e.Err) }
func (e *httpError) Unwrap() error { return e.Err }

// Turns a numeric range into one named condition callers can test.
func (e *httpError) Is(target error) bool {
	return target == ErrClientFault && e.Status >= 400 && e.Status < 500
}

// Returns a concrete pointer, not an error interface: comparing he == nil
// is then a plain pointer comparison with no typed-nil trap.
func handle(key, alias string) *httpError {
	err := link(key, alias)
	switch {
	case err == nil:
		return nil
	case errors.Is(err, ErrNotFound):
		return &httpError{404, err}
	case errors.Is(err, ErrConflict):
		return &httpError{409, err}
	case errors.Is(err, ErrInvalid):
		return &httpError{400, err}
	default:
		return &httpError{500, err} // unclassified means our bug, not their request
	}
}

func main() {
	cases := [][2]string{
		{"u1", "u3"},
		{"u9", "u3"},
		{"u1", "u2"},
		{"u1", "  "},
		{"", "u3"},
	}

	for _, c := range cases {
		he := handle(c[0], c[1])
		if he == nil {
			fmt.Printf("200 link %s -> %s\n", c[0], c[1])
			continue
		}

		// The client gets a class. The log gets the whole route.
		client := "unexpected error"
		if errors.Is(he, ErrClientFault) {
			client = "bad request"
		}
		fmt.Printf("%d %-15s log: %v\n", he.Status, client, he.Err)

		// And the operator gets the innermost frame, as data.
		var se *storeError
		if errors.As(he, &se) {
			fmt.Printf("    origin: op=%s key=%q\n", se.Op, se.Key)
		}
	}
}

Output:

200 link u1 -> u3
404 bad request     log: link u9: store get "u9": not found
    origin: op=get key="u9"
409 bad request     log: link u1: store put "u2": conflict
    origin: op=put key="u2"
400 bad request     log: link u1: invalid input
500 unexpected error log: link : store get "": empty key
    origin: op=get key=""

Read the log: column as a route and the design justifies itself. link u9: store get "u9": not found names the operation, then the storage call, then the cause, in the order a reader needs them: what we were doing, where it broke, why. No layer repeated its neighbour, and no layer wrote the word "failed". The whole message is 34 characters and answers every question a 3 a.m. pager would ask.

The handler never inspects a string. errors.Is against three sentinels does the classification, and because those sentinels live in the domain vocabulary rather than in the storage package, swapping the map for a real database cannot break handle -- the new backend just has to keep returning ErrNotFound and ErrConflict somewhere in its chain. This is the payoff for the layered wrapping: classification depends on the presence of a value, not on the depth at which it sits or the text around it.

The Is method on *httpError earns its keep in the two lines that set client. Both 404 and 409 answer errors.Is(he, ErrClientFault) truthfully without the calling code knowing that HTTP status codes exist, let alone which ranges mean what. That knowledge lives in exactly one method, so the day someone adds 422 the client-facing behaviour follows automatically.

The last case is the instructive one. fetch("") wraps an anonymous errors.New("empty key") that matches no sentinel, so the switch falls through to 500 and the client is told nothing specific -- correct, because an unclassified error means we have a bug and the caller cannot act on it. Yet errors.As still reaches the *storeError and prints op=get key="". Failing to classify an error is not the same as failing to diagnose it, and a good chain gives you the second even when the first goes wrong. Note also that the handler prints he.Err, not he: the status is already the first column, and printing the wrapper would repeat it as http 500: link ....


Common Mistakes

  1. Using %v when callers need to match. The message looks identical, so nothing fails at compile time and nothing fails in a smoke test -- only the caller's errors.Is silently starts returning false. Any error you document as "wraps ErrX" must use %w.
  2. Wrapping a nil error. fmt.Errorf("save: %w", err) with err == nil returns a non-nil error reading save: %!w(<nil>). Guard every wrap with if err != nil.
  3. Prefixing with "failed to" or "error". failed to link u9: failed to get u9: not found is twice as long and no more informative. The reader already knows it is an error.
  4. Comparing with == when the error is wrapped. err == ErrNotFound is false the instant any layer wraps it. Use errors.Is for sentinels, always, even where you believe nothing wraps today.
  5. Type-asserting instead of using errors.As. err.(*storeError) only inspects the outermost value, so it fails on exactly the wrapped errors you built the type for.
  6. Sentinels that are not comparable. errors.Is starts with ==; a sentinel declared as a struct containing a slice or map panics at runtime when compared. Sentinels should be errors.New values.
  7. Passing a non-pointer to errors.As. errors.As(err, se) panics; it needs &se. So does passing a pointer to something that is neither an error nor an interface.
  8. Forgetting Unwrap on a custom type. A type with Error() and an Err field but no Unwrap() error is a dead end: it prints the cause and hides it from every inspection function.
  9. Building the message by hand. errors.New("ctx: " + err.Error()) both severs the chain and crashes on a nil err. Use %v if severing is what you want.
  10. Wrapping the same error twice in one call path. A helper that wraps, called from a function that wraps again with the same noun, produces link u9: link u9: .... Decide which layer owns the noun.
  11. Wrapping context.Canceled as a failure. It travels up looking like a real error and gets logged, alerted on, and retried. Classify cancellation at the point you detect it.

Best Practices

  • Wrap once per layer, adding the one noun that layer knows: an operation name, a key, a request id.
  • Document the sentinels a function can wrap. "Returns an error wrapping ErrNotFound if the key is absent" is part of the signature, not a comment nicety.
  • Define sentinels in the package that owns the concept, not the package that happens to detect it, so backends can be swapped without touching callers.
  • Give custom error types both Error() string and Unwrap() error, and use a pointer receiver so errors.As(err, &target) has an obvious target type.
  • Reach for %v deliberately at API boundaries where the cause is an implementation detail you refuse to promise.
  • Use errors.Is for "which condition is this" and errors.As for "give me the details" -- never a string match on err.Error().
  • Add an Is(error) bool method when a range or category deserves one name, and keep it pure and cheap.
  • Classify at the boundary, once. Deep code returns errors; the handler decides what they mean and what the client is told.

Practice Exercises

  1. Wrap a chain and inspect it. Define ErrRateLimited, wrap it through three layers (fmt.Errorf twice plus one custom type with Unwrap), then prove with errors.Is that the sentinel is still reachable and with errors.Unwrap that each peel removes exactly one layer. Switch the middle %w to %v and observe which assertion breaks.
  2. Write a type ConfigError{File string; Line int; Err error} with Error, Unwrap, and a parser that returns it for three bad lines. In main, use errors.As to print the file and line for each, and errors.Is to distinguish a missing key from a bad value.
  3. Add a category via Is. Build type retryable struct{ Err error } whose Is method reports true for a package-level ErrRetryable, wrap two of five simulated failures in it, and write a loop that retries only those, printing one line per attempt.
  4. Combine wrapping with errors.Join. Validate a struct with four independent rules, join the failures, then wrap the joined error once with the record id. Show that errors.Is still finds each individual rule's sentinel through both the wrap and the join, and print how many rules failed.