Skip to content
Tutorials Center
My learning

Topics

Lesson 61 of 147 ยท Errors

Wrapping and Inspecting Errors

Learn how to add context to Go errors with fmt.Errorf and %w, inspect error chains with errors.Is, errors.As and errors.Unwrap, combine errors with errors.Join, and decide when not to wrap.

In Errors as Values you learned to return an error to your caller. But a bare open data.json: no such file or directory deep inside a large program does not tell you why the program was opening that file. Was it loading settings? Restoring a session? Importing a report? Good error messages read like a short story of what was being attempted: load settings: read data.json: no such file or directory.

Go adds this context by wrapping: a new error holds a message of its own plus the original error inside it. Wrapped errors form a chain that you can walk with errors.Is, errors.As and errors.Unwrap, so adding context never stops callers from recognizing the underlying cause. This lesson covers all of that, plus errors.Join for reporting several failures at once, and the design question of when you should deliberately not wrap.

Wrapping with %w

fmt.Errorf has a special verb, %w (for "wrap"). It formats the error like %v would, but also remembers it, so that the new error has an Unwrap method returning the original:

Go Wrapping adds context and keeps the cause

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The final message is the chain of contexts joined with colons, read from the outermost layer to the root cause: startup: read settings: open settings.json: no such file or directory. The loop shows every layer: two *fmt.wrapError values created by Errorf, then the *fs.PathError from the os package, and at the bottom the operating-system code (syscall.Errno) that started it all.

Write context as a short description of what this function was doing, not of what went wrong. The cause is already in the wrapped error. Good: fmt.Errorf("parse invoice %d: %w", id, err). Bad: fmt.Errorf("failed to parse invoice: error: %w", err), which stacks words like "failed" and "error" at every layer.

errors.Is: is this error, anywhere in the chain?

Once errors are wrapped, err == ErrNotFound no longer works, because err is now the outer wrapper. errors.Is(err, target) walks the whole chain and reports whether any error in it matches target:

Go errors.Is looks through the wrappers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

errors.Is compares each error in the chain with == (and also calls an Is method if the error has one; Custom Error Types shows how). It is the right replacement for every == against a sentinel error, and works fine on unwrapped errors too, so use it by default.

Wrapping with %v breaks the chain

Only %w records the cause. If you format the error with %v or %s, you get the text but lose the link:

Go %w versus %v

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Both messages look identical, but the flattened error has no cause: errors.Unwrap returns nil. This is occasionally what you want (see "When not to wrap" below), and a classic bug when it isn't.

errors.As: find an error of a given type

errors.Is answers "is it this error value?". Often you need "is it an error of this type, and if so, give me its fields". errors.As(err, &target) walks the chain looking for an error assignable to the type of target, and sets target to it:

Go errors.As extracts a typed error

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Study the shape of the call: you declare a variable of the error type you are looking for (here a pointer, *fs.PathError) and pass a pointer to that variable. If errors.As finds a match, it returns true and stores the error in your variable. Passing something that is not a pointer to an error-implementing type or an interface makes go vet complain and, at run time, panic.

You can also look for an interface. For example, the standard library's network errors have a Timeout() bool method; asking for that behaviour is more flexible than naming a concrete type:

Go errors.As with an interface

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Combining errors: errors.Join and multiple %w

Sometimes several things go wrong at once: validating a form with five bad fields, closing three resources of which two fail, or running tasks in parallel. Returning only the first error hides the rest. errors.Join (Go 1.20) combines any number of errors into one, separating the messages by newlines and skipping nil entries:

Go errors.Join collects several errors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

errors.Join returns nil when every argument is nil, so return errors.Join(errs...) works without a length check. Each error inside is still reachable: errors.Is and errors.As examine all of them. The joined error has an Unwrap() []error method (a slice, not a single error), which you use to iterate:

Go Joined errors and multiple %w

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

errors.Join separates messages with a newline, which is awkward in single-line log entries. If that matters, build a custom message with fmt.Errorf and several %w verbs, or format the list yourself.

When not to wrap

Wrapping makes the cause part of your function's public behaviour: callers can now write errors.Is(err, sql.ErrNoRows) and depend on it. If you later switch from one database library to another, every caller that tested for the old library's error breaks. Wrapping is therefore a decision about your API, not just about message text:

  • Inside a package or within one application layer: wrap freely with %w so that logs show the whole story.
  • At an API boundary where callers should not depend on the implementation: either translate the error into one of your own sentinel or custom errors, or format it with %v so the text survives but the cause is hidden.
Go Translating errors at a package boundary

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Callers can rely on ErrUserNotFound and nothing else. The text still contains the underlying detail, so logs stay useful.

Do not wrap just to wrap

A few more guidelines:

  • Do not repeat the callee's name in your message if the callee already includes it. os.ReadFile errors already contain the path, so fmt.Errorf("could not read file %s: %w", path, err) repeats it.
  • Return err unchanged when you have nothing useful to add; for instance in a thin wrapper that only delegates.
  • Do not wrap io.EOF carelessly. A reader loop that compares with == would stop matching; use errors.Is(err, io.EOF) in your own code, and remember that standard-library functions such as bufio.Reader.ReadString return io.EOF unwrapped on purpose.
  • Wrap each error once per layer, not in both the helper and its caller.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which verb makes fmt.Errorf keep the original error so errors.Is can find it?

    %w wraps its operand: the result has an Unwrap method returning the original error. %v and %s only copy the text.
  2. 2. After err := fmt.Errorf("read: %w", ErrNotFound), what is err == ErrNotFound?

    The wrapper is a different value. errors.Is(err, ErrNotFound) walks the chain and reports true.
  3. 3. What must you pass as the second argument of errors.As?

    errors.As stores the matching error into the variable you point to, so it needs a pointer to a variable such as var pe *fs.PathError.
  4. 4. What does errors.Join(nil, nil) return?

    Join discards nil errors, and returns nil if nothing is left, so return errors.Join(errs...) is safe for an empty slice.
  5. 5. Why might a library deliberately use %v instead of %w for an internal error?

    A wrapped cause can be matched by callers, who then depend on it. %v keeps the text for humans but hides the cause.

Summary

  • Wrap an error with fmt.Errorf("what I was doing: %w", err) to add context while keeping the cause. Messages read from outermost context to root cause.
  • errors.Is(err, target) checks every error in the chain; it replaces == for sentinel errors.
  • errors.As(err, &target) finds an error of a given type (or interface) in the chain and gives you access to its fields.
  • errors.Unwrap peels one layer; errors.Join and multiple %w combine several errors, and Is/As look into all of them.
  • %v flattens an error to text and breaks the chain, which can be useful at API boundaries so that callers do not depend on your internals.
  • Keep context short, do not repeat what the callee already says, and wrap once per layer.

Next: Custom Error Types builds your own error structs with fields, methods and Is/As support.