These are the notes for Go episode 25. Episode 24 made errors ordinary values: a function returns an error as its last result, the caller checks if err != nil, and sentinel errors like ErrNotOnMenu are compared with ==. But it ended with a problem. The moment you add context to an error ("order 7: item not on menu") with fmt.Errorf and %v, the caller can no longer recognise the original error. In this episode you invent the fix, error wrapping: the verb %w puts the original error inside the new one, errors.Unwrap opens one layer, a wrap chain is many layers, errors.Is searches the whole chain for a value and errors.As searches it for a type. errors.Join returns many errors as one. Then the strategy part: when to handle an error and when to propagate it, why you log once, what an opaque error is, the trade-offs between sentinels and error types, and where panics fit. The mini project checks an order file with a custom LineError that has its own Unwrap method. Every example runs as-is in the SyntaxPilot compiler (language: Go); outputs, compiler errors and panics are from real runs of go run main.go (Go 1.24, linux/amd64). Panic traces show /tmp/.../main.go where the real temporary folder was, and the +0x... numbers differ between machines and runs.
The problem: context breaks ==
Here is where episode 24 stopped. price returns the sentinel ErrNotOnMenu. bill adds context, meaning extra detail about where the error happened (which order), by building a new error with fmt.Errorf and the %v verb. main prints it and compares it with the sentinel, exactly like last episode.
package main
import (
"errors"
"fmt"
)
var ErrNotOnMenu = errors.New("item not on menu")
func price(item string) (float64, error) {
return 0, ErrNotOnMenu
}
func bill(order int, item string) error {
_, err := price(item)
if err != nil {
return fmt.Errorf("order %d: %v", order, err)
}
return nil
}
func main() {
err := bill(7, "dosa")
fmt.Println(err)
fmt.Println(err == ErrNotOnMenu)
}
order 7: item not on menu
false
- The message is better than before:
order 7: item not on menu. A person reading the log knows which order failed. - But
err == ErrNotOnMenuis false. The program can no longer tell that the item was missing, so it can't react, for example by suggesting chai instead. - Why it failed:
%vformats the old error as text and builds a brand new error from that text: a plain*errors.errorString, the same kinderrors.Newmakes. The original value, the one everybody compares against, is thrown away. Only its message survived. - We want both: more context, and the original kept inside.
Wrapping with %w
Think of a courier office.
| At the courier office | In Go | Name |
|---|---|---|
| The original parcel: "item not on menu" | ErrNotOnMenu |
the original (inner) error |
| Each office puts it in a bigger box and writes its label: "order 7" | fmt.Errorf("order 7: %w", err) |
wrapping |
| Anyone can open the outer box and find the parcel | errors.Unwrap(err) |
unwrapping one layer |
- Wrapping an error means making a new error that carries the old error inside it, plus extra context. Nothing is lost: the old error is still there, untouched.
- In Go you wrap with the
%wverb offmt.Errorfinstead of%v. Thewstands for wrap. The message looks exactly the same; the difference is what's inside. errors.Unwrap(err)returns the error thaterrwraps, one layer in. Iferrdoesn't wrap anything, it returnsnil.
Same program, one letter changed, plus two Unwrap calls:
package main
import (
"errors"
"fmt"
)
var ErrNotOnMenu = errors.New("item not on menu")
func price(item string) (float64, error) {
return 0, ErrNotOnMenu
}
func bill(order int, item string) error {
_, err := price(item)
if err != nil {
return fmt.Errorf("order %d: %w", order, err)
}
return nil
}
func main() {
err := bill(7, "dosa")
fmt.Println(err)
fmt.Println(err == ErrNotOnMenu)
inner := errors.Unwrap(err)
fmt.Println(inner == ErrNotOnMenu)
fmt.Println(errors.Unwrap(inner))
}
order 7: item not on menu
false
true
<nil>
- Same message.
err == ErrNotOnMenuis stillfalse: the outer box is a different value from the parcel inside it.errors.Unwrap(err) == ErrNotOnMenuistrue: the original sentinel is inside.errors.Unwrap(inner)prints<nil>: a sentinel made byerrors.Newwraps nothing.
You just invented error wrapping.
How %w works
fmt.Errorf looks at its format string. If it contains %w with an error argument, it returns a value of the unexported type *fmt.wrapError, which stores the formatted message and the wrapped error, and has a method Unwrap() error. errors.Unwrap simply calls that method. Without %w, fmt.Errorf returns the same kind of plain error as errors.New. You can see the type with %T in the next section.
Wrap chains and errors.Is
Real programs have many layers of functions. Each one adds its piece of context: price wraps the sentinel with the item name, bill wraps that with the order number, checkout wraps that again. Boxes inside boxes inside boxes: a wrap chain (also called an error chain). The loop below walks the chain with errors.Unwrap and prints each layer's type with %T.
package main
import (
"errors"
"fmt"
)
var ErrNotOnMenu = errors.New("item not on menu")
func price(item string) error {
return fmt.Errorf("price %q: %w", item, ErrNotOnMenu)
}
func bill(order int) error {
if err := price("dosa"); err != nil {
return fmt.Errorf("order %d: %w", order, err)
}
return nil
}
func checkout() error {
if err := bill(7); err != nil {
return fmt.Errorf("checkout: %w", err)
}
return nil
}
func main() {
err := checkout()
fmt.Println(err)
for e := err; e != nil; e = errors.Unwrap(e) {
fmt.Printf(" %T\n", e)
}
fmt.Println(err == ErrNotOnMenu)
fmt.Println(errors.Is(err, ErrNotOnMenu))
}
checkout: order 7: price "dosa": item not on menu
*fmt.wrapError
*fmt.wrapError
*fmt.wrapError
*errors.errorString
false
true
- One readable message, built from the outside in:
checkout: order 7: price "dosa": item not on menu. Every layer added its own prefix. This is why Go error messages are lowercase with no ending punctuation (episode 24): they get glued together like this. - The loop shows three
*fmt.wrapErrorlayers and then the sentinel itself, an*errors.errorString. err == ErrNotOnMenu: false.errors.Is(err, ErrNotOnMenu): true.errors.Isunwraps layer after layer, and at each one asks "is this the target?". You never have to count layers.
Rule of thumb: once errors can be wrapped (and in real code they always can), compare sentinels with errors.Is, never with ==.
if errors.Is(err, ErrNotOnMenu) { /* suggest chai */ }
if errors.Is(err, io.EOF) { /* finished reading */ }
Wrapping in one page
| You write | You get | Original findable? |
|---|---|---|
fmt.Errorf("order %d: %v", id, err) |
new message, text only | no |
fmt.Errorf("order %d: %w", id, err) |
new message + original inside | yes |
errors.Unwrap(err) |
the error one layer in, or nil |
— |
errors.Is(err, target) |
true if target is anywhere in the chain |
— |
errors.As(err, &target) |
true if an error of target's type is in the chain; stores it |
— |
errors.As for custom types
Episode 24's custom error type OutOfStock carries data: how many samosas are left. We got it back with a type assertion (err.(*OutOfStock)). Now order wraps it with the order number. Does the type assertion still work?
package main
import (
"errors"
"fmt"
)
type OutOfStock struct {
Item string
Left int
}
func (e *OutOfStock) Error() string {
return fmt.Sprintf("%s out of stock (%d left)", e.Item, e.Left)
}
func order(id, qty int) error {
if qty > 3 {
err := &OutOfStock{"samosa", 3}
return fmt.Errorf("order %d: %w", id, err)
}
return nil
}
func main() {
err := order(7, 5)
fmt.Println(err)
_, ok := err.(*OutOfStock)
fmt.Println("assertion:", ok)
var oos *OutOfStock
if errors.As(err, &oos) {
fmt.Println("As: offer", oos.Left, "of", oos.Item)
}
}
order 7: samosa out of stock (3 left)
assertion: false
As: offer 3 of samosa
- Assertion: false. A type assertion only looks at the outer value, which is now an
*fmt.wrapError, not an*OutOfStock. errors.As(err, &target)searches the chain for the first error whose type matchestarget's type. If it finds one, it stores it intargetand returnstrue. Hereoosbecomes the*OutOfStockfrom inside, sooos.Leftis 3.- The second argument is a pointer to your variable (
&oos), becauseerrors.Ashas to write into it.
Is or As? Two questions at the parcel counter
| Question | Go | Use for |
|---|---|---|
| "Is my phone in here?" (one exact thing) | errors.Is(err, ErrX) |
sentinel values |
| "Is any book in here? Hand it over." (any thing of a kind) | errors.As(err, &target) |
custom error types with data |
errors.Is answers yes or no. errors.As answers yes or no and gives you the error so you can read its fields.
Wrapping mistakes
%w with something that isn't an error
package main
import (
"errors"
"fmt"
)
var ErrNotOnMenu = errors.New("item not on menu")
func main() {
msg := "item not on menu"
err := fmt.Errorf("order 7: %w", msg)
fmt.Println(err)
fmt.Println(errors.Is(err, ErrNotOnMenu))
}
order 7: %!w(string=item not on menu)
false
fmtmarks the bad argument as%!w(string=...):%wneeds a value of typeerror, andmsgis astring.- Nothing was wrapped, so
errors.Isisfalse. go vet(the checker from episode 2) catches it before you run:
./main.go:12:12: fmt.Errorf format %w has arg msg of wrong type string
errors.As without the &
package main
import (
"errors"
"fmt"
)
type OutOfStock struct{ Item string }
func (e *OutOfStock) Error() string { return e.Item + " out of stock" }
func main() {
err := fmt.Errorf("order 7: %w", &OutOfStock{"samosa"})
var oos *OutOfStock
fmt.Println(errors.As(err, oos))
}
panic: errors: target must be a non-nil pointer
goroutine 1 [running]:
errors.As({0x4e1838?, 0xc000128000?}, {0x4a4f00?, 0x0?})
/usr/local/go1.24.7/src/errors/wrap.go:107 +0x218
main.main()
/tmp/.../main.go:15 +0x6d
exit status 2
oosis a nil*OutOfStock.errors.Asneeds somewhere to write the result, so it needs the address of your variable:&oos. Passing the variable itself is a panic (a crash for a programming bug; episode 26).go vetcatches this one too:
./main.go:15:17: second argument to errors.As must be a non-nil pointer to either a type that implements error, or to any interface type
errors.Join: many errors at once
New problem: an order form with a name, a quantity and a phone number. check returns at the first problem it finds, and a customer fills in everything wrong.
package main
import (
"errors"
"fmt"
)
func check(name string, qty int, phone string) error {
if name == "" {
return errors.New("name is empty")
}
if qty <= 0 {
return fmt.Errorf("qty %d must be positive", qty)
}
if len(phone) != 10 {
return fmt.Errorf("phone %q needs 10 digits", phone)
}
return nil
}
func main() {
fmt.Println(check("", 0, "98765"))
}
name is empty
- They fix the name and submit again: now the quantity is wrong. Again: now the phone. Three round trips for three mistakes.
- Why: one
errorresult holds one error. We want to report them all at once.
errors.Join(errs ...error) error takes any number of errors and joins them into one. From go doc errors.Join: it "returns an error that wraps the given errors. Any nil error values are discarded. Join returns nil if every value in errs is nil." Its message is each error's message with a newline between them.
package main
import (
"errors"
"fmt"
)
var ErrEmpty = errors.New("name is empty")
func check(name string, qty int, phone string) error {
var errs []error
if name == "" {
errs = append(errs, ErrEmpty)
}
if qty <= 0 {
errs = append(errs, fmt.Errorf("qty %d must be positive", qty))
}
if len(phone) != 10 {
errs = append(errs, fmt.Errorf("phone %q needs 10 digits", phone))
}
return errors.Join(errs...)
}
func main() {
err := check("", 0, "98765")
fmt.Println(err)
fmt.Println("---")
fmt.Println(errors.Is(err, ErrEmpty))
fmt.Println(check("Asha", 2, "9876543210") == nil)
}
name is empty
qty 0 must be positive
phone "98765" needs 10 digits
---
true
true
- All three problems, one per line.
errors.Is(err, ErrEmpty)still finds the sentinel inside the joined error:IsandAssearch every joined error.- A good form gives
nil(the lasttrue), so the usualif err != nilstill works. - The pattern: collect problems in a
[]error, thenreturn errors.Join(errs...)at the end. The...passes a slice to a variadic function (episode 9).
Handle or propagate
Every time a function gets an error, it has two choices:
| In a restaurant | In Go | Name |
|---|---|---|
| The cook runs out of coriander and uses mint | deal with it right here; nothing goes further | handle the error |
| The waiter can't make a dish appear; he tells the manager why | return fmt.Errorf("...: %w", err) |
propagate the error (pass it up, with context) |
| The manager writes it in the day book once | log it at the top | log once |
| Cook, waiter and manager all write it down | three log lines, one problem | noise |
- Handling an error means the code can do something sensible about it (use a default, retry, skip one item, ask the user again), so the error stops there.
- Propagating an error means returning it to your caller (the function that called you), usually wrapped with context, because you can't fix it yourself.
Log once
Logging means writing a message to a record of what the program did (the screen, a file, a log service), so people can investigate later. Here every layer logs the error and returns it:
package main
import (
"errors"
"fmt"
)
var ErrNotOnMenu = errors.New("item not on menu")
func price(item string) error {
err := fmt.Errorf("price %q: %w", item, ErrNotOnMenu)
fmt.Println("LOG:", err)
return err
}
func bill(order int) error {
err := price("dosa")
if err != nil {
fmt.Println("LOG:", err)
return fmt.Errorf("order %d: %w", order, err)
}
return nil
}
func main() {
if err := bill(7); err != nil {
fmt.Println("LOG:", err)
}
}
LOG: price "dosa": item not on menu
LOG: price "dosa": item not on menu
LOG: order 7: price "dosa": item not on menu
- One missing dosa, three log lines. On a busy server with thousands of requests, the logs fill with copies, and nobody can tell how many failures really happened.
- The rule: either handle an error, or return it, not both. If you return it, add context instead of logging. The one place that finally handles it (often
main, or the top of a web request) logs it once, with all the context the layers added.
The fixed version (only main logs):
package main
import (
"errors"
"fmt"
)
var ErrNotOnMenu = errors.New("item not on menu")
func price(item string) error {
return fmt.Errorf("price %q: %w", item, ErrNotOnMenu)
}
func bill(order int) error {
if err := price("dosa"); err != nil {
return fmt.Errorf("order %d: %w", order, err)
}
return nil
}
func main() {
if err := bill(7); err != nil {
fmt.Println("LOG:", err)
}
}
LOG: order 7: price "dosa": item not on menu
Both choices in one program
bill needs a discount from a coupon service, which is down. That's not worth failing the order for, so bill handles it: no discount. A dish that isn't on the menu is something bill can't fix, so it wraps and returns it.
package main
import (
"errors"
"fmt"
)
var ErrNotOnMenu = errors.New("item not on menu")
var ErrNoCoupon = errors.New("coupon service down")
func discount(code string) (float64, error) {
return 0, ErrNoCoupon
}
func bill(item string, code string) (float64, error) {
if item != "chai" {
return 0, fmt.Errorf("bill %q: %w", item, ErrNotOnMenu)
}
off, err := discount(code)
if errors.Is(err, ErrNoCoupon) {
off = 0 // handled here: bill without a discount
}
return 10 - off, nil
}
func main() {
fmt.Println(bill("chai", "DIWALI"))
total, err := bill("dosa", "")
if err != nil {
fmt.Println("LOG once:", err)
return
}
fmt.Println(total)
}
10 <nil>
LOG once: bill "dosa": item not on menu
10 <nil>: chai cost 10 with no error. The coupon failure was handled; the customer still got their chai. (fmt.Printlnprints both results ofbill.)- The dosa error travelled up and
mainlogged it once. - Notice
errors.Is(err, ErrNoCoupon): handling one specific error and letting the others through is exactly what sentinels anderrors.Isare for.
Opaque errors, sentinels or types?
When you write a package, you decide what callers can see inside your errors.
| Kind | How | Callers can | Cost |
|---|---|---|---|
| Opaque error | fmt.Errorf("load menu: %v", err), errors.New(...) not exported |
only check err != nil and read the message |
none: you may change the details freely |
| Sentinel error | var ErrNotOnMenu = errors.New(...) (exported) |
errors.Is(err, ErrNotOnMenu) |
it's part of your API; can't carry data |
| Error type | type OutOfStock struct{ Left int } (exported) |
errors.As(err, &oos) and read fields |
part of your API; more code |
Wrapping with %w |
fmt.Errorf("...: %w", err) |
see the inner error too | the inner error becomes part of your API |
- Opaque means "you can't see through it". An opaque error says that something failed, not what kind of thing. Its advantage: you're free to change it later without breaking anyone.
- An API (application programming interface) is the set of names and behaviours a package promises to the code that uses it. Once callers write
errors.Is(err, menu.ErrNotOnMenu), you can't remove or change that sentinel without breaking them. - Sentinels are simple and best for one fixed situation (
io.EOF,fs.ErrNotExist). - Types are best when the caller needs data (
*fs.PathErrorhasOpandPath;*strconv.NumErrorhasFuncandNum). - Because
%wexposes the inner error, wrap with%wonly when you want callers to depend on it. Use%vto deliberately hide it, for example an internal database error you might replace later.
Errors vs panics
| Error | Panic | |
|---|---|---|
| For | expected failures: missing file, bad input, network down | bugs and impossible states: index out of range, nil map write |
| What happens | returned as a value; the caller decides | normal execution stops; the program crashes unless recovered |
| Libraries | return errors | don't let panics escape to callers |
- A panic stops the program (you've seen
index out of rangeandnil pointer dereference). It's for programming mistakes, not for things that can normally go wrong. - Code that other people use should return errors. How panics work, and how to recover from one, is episode 26.
Mini project: an order file checker
Check every line of an order and report all the problems at once. LineError is a custom error type with the line number and the error inside. Its Unwrap method returns the inner error: that one method makes your type part of the chain, so errors.Is and errors.As can look inside it, just like %w.
package main
import (
"errors"
"fmt"
"strconv"
)
var ErrNotOnMenu = errors.New("not on menu")
var menu = map[string]int{"chai": 10, "samosa": 15}
type LineError struct{ Line int; Err error }
func (e *LineError) Error() string { return fmt.Sprintf("line %d: %v", e.Line, e.Err) }
func (e *LineError) Unwrap() error { return e.Err }
func parse(n int, item, qtyText string) (int, error) {
qty, err := strconv.Atoi(qtyText)
if _, ok := menu[item]; !ok {
err = fmt.Errorf("%q %w", item, ErrNotOnMenu)
}
if err != nil {
return 0, &LineError{n, err}
}
return menu[item] * qty, nil
}
func main() {
errs, total := []error{}, 0
for i, l := range [][2]string{{"chai", "2"}, {"samosa", "two"}, {"dosa", "1"}, {"samosa", "3"}} {
amt, err := parse(i+1, l[0], l[1])
errs = append(errs, err)
total += amt
}
err := errors.Join(errs...)
fmt.Println(err)
var ne *strconv.NumError
fmt.Println(errors.Is(err, ErrNotOnMenu), errors.As(err, &ne), ne.Num, total)
}
line 2: strconv.Atoi: parsing "two": invalid syntax
line 3: "dosa" not on menu
true true two 65
parseconverts the quantity withstrconv.Atoi("ASCII to integer", episode 24). If the dish is missing, it wrapsErrNotOnMenuwith%w. Any error goes back inside aLineErrorwith the line number.maincollects every result's error (includingnils from good lines) and joins them.errors.Joinskipped the nils: only lines 2 and 3 appear.errors.Is(err, ErrNotOnMenu):true. It went through the Join, then ourLineError(via itsUnwrap), then the%wwrap.errors.As(err, &ne)found the*strconv.NumError(the error typeAtoireturns) andne.Numis the text it failed on:two.65: the good lines, 2 chai (20) and 3 samosas (45).type LineError struct{ Line int; Err error }puts both fields on one line with a semicolon so the program fits on screen;gofmtwould normally put each field on its own line.
Extended version: line text, a format check and counting the kinds of problems
This version keeps the line text in the error, accepts dish names with spaces (vada pav), and counts each kind of problem by walking the joined error. A joined error has the method Unwrap() []error (a slice), so we get at the individual errors with a type assertion to an interface with that method.
package main
import (
"errors"
"fmt"
"strconv"
"strings"
)
var ErrNotOnMenu = errors.New("not on menu")
var menu = map[string]int{"chai": 10, "samosa": 15, "vada pav": 20}
type LineError struct {
Line int
Text string
Err error
}
func (e *LineError) Error() string {
return fmt.Sprintf("line %d (%q): %v", e.Line, e.Text, e.Err)
}
func (e *LineError) Unwrap() error { return e.Err }
func parse(n int, s string) (int, error) {
i := strings.LastIndex(s, " ")
if i < 0 {
return 0, &LineError{n, s, errors.New("want: item qty")}
}
item, qtyText := s[:i], s[i+1:]
p, ok := menu[item]
if !ok {
return 0, &LineError{n, s, fmt.Errorf("%q %w", item, ErrNotOnMenu)}
}
qty, err := strconv.Atoi(qtyText)
if err != nil {
return 0, &LineError{n, s, err}
}
return p * qty, nil
}
func check(lines []string) (int, error) {
var errs []error
total := 0
for i, s := range lines {
amt, err := parse(i+1, s)
if err != nil {
errs = append(errs, err)
continue
}
total += amt
}
return total, errors.Join(errs...)
}
func main() {
lines := []string{"chai 2", "samosa two", "dosa 1", "vada pav 1", "masala"}
total, err := check(lines)
fmt.Println("total:", total)
if err == nil {
return
}
fmt.Println(err)
kinds := map[string]int{}
u := err.(interface{ Unwrap() []error })
for _, e := range u.Unwrap() {
var ne *strconv.NumError
switch {
case errors.Is(e, ErrNotOnMenu):
kinds["not on menu"]++
case errors.As(e, &ne):
kinds["bad number"]++
default:
kinds["bad format"]++
}
}
fmt.Println(kinds)
}
total: 40
line 2 ("samosa two"): strconv.Atoi: parsing "two": invalid syntax
line 3 ("dosa 1"): "dosa" not on menu
line 5 ("masala"): want: item qty
map[bad format:1 bad number:1 not on menu:1]
strings.LastIndex(s, " ")finds the last space, sovada pav 1splits intovada pavand1.checkreturns the total of the good lines and the joined error: a function can return useful partial results together with an error, as long as its documentation says so.- The
switchwith no condition (episode 7) trieserrors.Is, thenerrors.As, then falls back to "bad format". fmt.Printlnprints map keys in sorted order, so the last line is the same on every run.
Expert corner
Wrapping two errors at once: %w twice
Since Go 1.20, fmt.Errorf accepts more than one %w. The result wraps all of them.
package main
import (
"errors"
"fmt"
)
var ErrNotOnMenu = errors.New("item not on menu")
var ErrClosed = errors.New("shop is closed")
func main() {
err := fmt.Errorf("order 7: %w; also %w", ErrNotOnMenu, ErrClosed)
fmt.Println(err)
fmt.Printf("%T\n", err)
fmt.Println(errors.Is(err, ErrNotOnMenu), errors.Is(err, ErrClosed))
fmt.Println(errors.Unwrap(err))
j := errors.Join(ErrNotOnMenu, ErrClosed)
fmt.Printf("%T\n", j)
fmt.Println(errors.Unwrap(j))
if u, ok := j.(interface{ Unwrap() []error }); ok {
fmt.Println(len(u.Unwrap()), "errors inside")
}
fmt.Println(errors.Join(nil, nil) == nil)
}
order 7: item not on menu; also shop is closed
*fmt.wrapErrors
true true
<nil>
*errors.joinError
<nil>
2 errors inside
true
- With two
%ws the type is*fmt.wrapErrors(plural), anderrors.Isfinds both sentinels. errors.Unwrapreturnsnilfor it, and for a joined error too.errors.Unwraponly calls a methodUnwrap() error. Errors that wrap several errors haveUnwrap() []errorinstead, whicherrors.Isanderrors.Asunderstand buterrors.Unwrapdoes not. So prefererrors.Is/errors.Asover callingerrors.Unwrapyourself.errors.Join(nil, nil) == nilistrue.
Custom Is and As methods
errors.Is compares each error in the chain with ==, but a type can also define a method Is(target error) bool to say "treat me as this sentinel":
package main
import (
"errors"
"fmt"
)
var ErrNotFound = errors.New("not found")
type MissingItem struct{ Item string }
func (e *MissingItem) Error() string { return e.Item + " is missing" }
// Is lets errors.Is treat a *MissingItem as ErrNotFound.
func (e *MissingItem) Is(target error) bool { return target == ErrNotFound }
func main() {
err := fmt.Errorf("order 7: %w", &MissingItem{"dosa"})
fmt.Println(err)
fmt.Println(errors.Is(err, ErrNotFound))
}
order 7: dosa is missing
true
Similarly a type may define As(target any) bool. Use these rarely: most code never needs them.
errors.As with an interface target
The target of errors.As can be a pointer to an interface type. Then As finds the first error in the chain that has those methods:
package main
import (
"errors"
"fmt"
)
type temporary interface{ Temporary() bool }
type Busy struct{}
func (Busy) Error() string { return "kitchen busy" }
func (Busy) Temporary() bool { return true }
func main() {
err := fmt.Errorf("order 7: %w", Busy{})
var t temporary
if errors.As(err, &t) {
fmt.Println("retry later?", t.Temporary())
}
var b Busy
fmt.Println(errors.As(err, &b), b)
}
retry later? true
true kitchen busy
Busy has a value receiver, so the target is a Busy, not a *Busy. Getting this wrong gives false, not an error: see quiz question 4.
Where errors.Is and errors.As stop
Both walk the tree of errors: a plain wrap has one child, a Join or two-%w error has several, and they search depth-first. They stop at the first match. An error with no Unwrap method is a leaf.
Common mistakes (and the real messages)
| Mistake | What you see | Why | Fix |
|---|---|---|---|
fmt.Errorf("order 7: %v", err) then err == ErrNotOnMenu |
false |
%v copies the text only |
wrap with %w, check with errors.Is |
err == ErrNotOnMenu on a wrapped error |
false |
== compares only the outer value |
errors.Is(err, ErrNotOnMenu) |
err.(*OutOfStock) on a wrapped error |
ok is false |
a type assertion sees only the outer value | errors.As(err, &oos) |
fmt.Errorf("... %w", "text") |
%!w(string=text); vet: fmt.Errorf format %w has arg msg of wrong type string |
%w needs an error |
pass an error value |
errors.As(err, oos) |
panic: errors: target must be a non-nil pointer |
As must write into the target |
errors.As(err, &oos) |
| returning only the first validation error | name is empty (and nothing else) |
one error per result | collect, then errors.Join(errs...) |
| log the error and return it at every layer | the same failure logged 3 times | handled twice | wrap and return; log once at the top |
errors.Unwrap on a joined error |
<nil> |
it only follows Unwrap() error |
errors.Is / errors.As |
Practice
- (Homework) Wrap a sentinel
ErrDivByZeroin two layers (divide→average→splitBill) and check it inmainwitherrors.Is. - (Homework) A custom
InsufficientFundserror withNeedandHave, wrapped bywithdraw. Starting with 500, withdraw 200 and then 450; read the fields witherrors.Asand print how much is missing. - (Homework) Validate a sign-up form (username, email with
@, password of at least 8 characters) and report every problem witherrors.Join. Make "username is required" findable witherrors.Is. - (Homework) Give a custom error type
ConfigError{File, Err}anUnwrapmethod, wrapfs.ErrNotExistin it, and check it witherrors.Is. - Fix the "log at every layer" program from the video so the failure is logged exactly once, with all its context.
Solutions
- Each layer wraps with
%w;errors.Issees through both.
package main
import (
"errors"
"fmt"
)
var ErrDivByZero = errors.New("division by zero")
func divide(a, b int) (int, error) {
if b == 0 {
return 0, ErrDivByZero
}
return a / b, nil
}
func average(total, people int) (int, error) {
avg, err := divide(total, people)
if err != nil {
return 0, fmt.Errorf("average of %d: %w", total, err)
}
return avg, nil
}
func splitBill(total, people int) error {
each, err := average(total, people)
if err != nil {
return fmt.Errorf("split bill: %w", err)
}
fmt.Println("each pays", each)
return nil
}
func main() {
for _, n := range []int{4, 0} {
err := splitBill(200, n)
if errors.Is(err, ErrDivByZero) {
fmt.Println(err, "-> ask how many people")
}
}
}
each pays 50
split bill: average of 200: division by zero -> ask how many people
withdrawwraps the custom error;errors.Asdigs it out.
package main
import (
"errors"
"fmt"
)
type InsufficientFunds struct{ Need, Have int }
func (e *InsufficientFunds) Error() string {
return fmt.Sprintf("need %d, have %d", e.Need, e.Have)
}
func withdraw(balance, amount int) (int, error) {
if amount > balance {
return balance, fmt.Errorf("withdraw %d: %w", amount, &InsufficientFunds{amount, balance})
}
return balance - amount, nil
}
func main() {
bal := 500
for _, amt := range []int{200, 450} {
var err error
bal, err = withdraw(bal, amt)
var f *InsufficientFunds
if errors.As(err, &f) {
fmt.Println(err, "| missing:", f.Need-f.Have)
continue
}
fmt.Println("ok, balance", bal)
}
}
ok, balance 300
withdraw 450: need 450, have 300 | missing: 150
- Collect, then join.
package main
import (
"errors"
"fmt"
"strings"
)
var ErrRequired = errors.New("required")
func signup(user, email, pass string) error {
var errs []error
if user == "" {
errs = append(errs, fmt.Errorf("username: %w", ErrRequired))
}
if !strings.Contains(email, "@") {
errs = append(errs, fmt.Errorf("email %q: missing @", email))
}
if len(pass) < 8 {
errs = append(errs, fmt.Errorf("password: %d characters, need 8", len(pass)))
}
return errors.Join(errs...)
}
func main() {
err := signup("", "neha.example.com", "chai")
fmt.Println(err)
fmt.Println("required missing?", errors.Is(err, ErrRequired))
fmt.Println(signup("neha", "neha@example.com", "masala123") == nil)
}
username: required
email "neha.example.com": missing @
password: 4 characters, need 8
required missing? true
true
- One
Unwrapmethod makes the type part of the chain.
package main
import (
"errors"
"fmt"
"io/fs"
)
type ConfigError struct {
File string
Err error
}
func (e *ConfigError) Error() string { return "config " + e.File + ": " + e.Err.Error() }
func (e *ConfigError) Unwrap() error { return e.Err }
func main() {
err := &ConfigError{"shop.toml", fs.ErrNotExist}
fmt.Println(err)
fmt.Println(errors.Is(err, fs.ErrNotExist))
}
config shop.toml: file does not exist
true
priceandbillonly wrap and return;mainlogs once. The program is shown in the "Log once" section above; its output is the single lineLOG: order 7: price "dosa": item not on menu.
Quick quiz
1. What does this print? (From the video.)
package main
import (
"errors"
"fmt"
)
var ErrClosed = errors.New("closed")
func open(h int) error {
return fmt.Errorf("hour %d: %w", h, ErrClosed)
}
func main() {
err := fmt.Errorf("shop: %w", open(23))
fmt.Println(err == ErrClosed, errors.Is(err, ErrClosed))
}
A. true true · B. false true · C. false false · D. true false
Answer
B. err is two boxes around ErrClosed, so == is false. errors.Is opens both boxes: true. Real output: false true.
2. What does this print?
package main
import (
"errors"
"fmt"
)
var ErrClosed = errors.New("closed")
func main() {
a := fmt.Errorf("shop: %v", ErrClosed)
b := fmt.Errorf("shop: %w", ErrClosed)
fmt.Println(a.Error() == b.Error(), errors.Is(a, ErrClosed), errors.Is(b, ErrClosed))
}
Answer
true false true. Both messages are the same text (shop: closed), but only the %w one keeps ErrClosed inside.
3. What does this print?
package main
import (
"errors"
"fmt"
)
func main() {
var errs []error
errs = append(errs, nil, nil)
err := errors.Join(errs...)
fmt.Println(err == nil)
}
Answer
true. errors.Join discards nil values and returns nil when every value is nil, so if err != nil works as usual.
4. OutOfStock has a value receiver here. What does this print?
package main
import (
"errors"
"fmt"
)
type OutOfStock struct{ Left int }
func (e OutOfStock) Error() string { return "out of stock" }
func main() {
err := fmt.Errorf("order 7: %w", OutOfStock{3})
var p *OutOfStock
var v OutOfStock
fmt.Println(errors.As(err, &p), errors.As(err, &v), v.Left)
}
Answer
false true 3. The chain holds an OutOfStock value, not a *OutOfStock, so the pointer target doesn't match. Match the target's type to what was actually wrapped.
5. A function both logs an error and returns it, and so does its caller. What goes wrong?
Answer
The same failure is logged twice (or more), so the logs overstate how many failures happened and are harder to read. Handle or return; log once at the top.
Interview questions
- What is the difference between
%vand%winfmt.Errorf? Both produce the same message.%walso keeps the original error inside (the result has anUnwrapmethod), soerrors.Isanderrors.Ascan find it;%vkeeps only the text. - Why use
errors.Isinstead of==?==compares only the outermost error. Once an error is wrapped, the sentinel is inside;errors.Issearches the whole chain (and joined errors). - When do you use
errors.As? To find an error of a particular type anywhere in the chain and get its data, e.g.*fs.PathError'sPathor*strconv.NumError'sNum. Pass a pointer to a variable of that type. - How do you make your own error type work with
errors.Isanderrors.As? Give it a methodUnwrap() errorthat returns the inner error (orUnwrap() []errorfor several). - What does
errors.Joinreturn when every argument is nil?nil. Non-nil arguments are kept; the message has one line per error. - What does "handle or return, not both" mean? If a function can fix an error, it handles it and doesn't return it. If it can't, it returns it with context and doesn't log it, so each failure is logged exactly once, at the top.
- When should you NOT wrap with
%w? When you don't want callers to depend on the inner error, e.g. an implementation detail like a specific database driver's error. Wrapping makes the inner error part of your API. - Sentinel error or error type? A sentinel for one fixed condition with no extra data (
io.EOF). A type when callers need details (*fs.PathError). Both are part of your API once exported. - Errors or panics? Errors for expected failures; panics for bugs and impossible states. Libraries return errors.
Glossary
| Term | Meaning | Example |
|---|---|---|
| Context (in an error) | extra detail about where an error happened, added as a prefix | order 7: item not on menu |
| Wrapping | making a new error that keeps the old error inside it, plus context | fmt.Errorf("order 7: %w", err) |
%w |
the fmt.Errorf verb that wraps its error argument ("w" for wrap) |
fmt.Errorf("checkout: %w", err) |
%v |
formats a value as text; with an error it copies only the message | fmt.Errorf("order 7: %v", err) |
%!w(...) |
what fmt prints when %w gets a non-error argument |
%!w(string=item not on menu) |
Unwrap method |
Unwrap() error: returns the error inside; makes a type part of a chain |
func (e *LineError) Unwrap() error |
errors.Unwrap |
calls Unwrap() error once; nil if there is nothing inside |
errors.Unwrap(err) == ErrNotOnMenu |
| Wrap chain / error chain | errors wrapped inside errors, layer after layer | checkout → order 7 → price → ErrNotOnMenu |
*fmt.wrapError |
the unexported type fmt.Errorf returns when it has one %w |
%T of a wrapped error |
*fmt.wrapErrors |
the type returned for two or more %w verbs |
fmt.Errorf("%w; %w", a, b) |
errors.Is |
reports whether a given error value is anywhere in the chain | errors.Is(err, ErrNotOnMenu) |
errors.As |
finds the first error of a given type in the chain and stores it in a target | errors.As(err, &oos) |
Target (of errors.As) |
a pointer to the variable As fills in |
var oos *OutOfStock; &oos |
errors.Join |
combines many errors into one; drops nils; nil if all are nil | errors.Join(errs...) |
*errors.joinError |
the type errors.Join returns; has Unwrap() []error |
%T of a joined error |
Unwrap() []error |
the method of errors that wrap several errors | joined errors, two-%w errors |
| Sentinel error | one fixed, exported error value compared by identity (episode 24) | ErrNotOnMenu, io.EOF |
| Custom error type | your own type with an Error() string method, carrying data (episode 24) |
*OutOfStock{Item, Left} |
| Type assertion | getting the concrete value out of an interface; sees only the outer error | err.(*OutOfStock) |
| Handle (an error) | deal with it where it happens so it goes no further | use no discount when the coupon service is down |
| Propagate (an error) | return it to your caller, usually wrapped with context | return fmt.Errorf("bill: %w", err) |
| Caller | the function that called the current function | main is bill's caller |
| Logging | writing a record of what the program did, for people to read later | fmt.Println("LOG:", err), log.Println |
| Log once | log a failure only where it is finally handled, never at every layer | log in main only |
| Opaque error | an error callers can't look inside; they only know it failed | fmt.Errorf("load menu: %v", err) |
| API | the names and behaviour a package promises to its users | exported ErrNotOnMenu |
| Error types vs sentinels | types carry data and are found with As; sentinels are single values found with Is |
*fs.PathError vs fs.ErrNotExist |
| Panic | stops normal execution; for bugs, not expected failures (episode 26) | panic: errors: target must be a non-nil pointer |
go vet |
Go's checker for suspicious code (episode 2) | fmt.Errorf format %w has arg msg of wrong type string |
Variadic call with ... |
passing a slice's elements as separate arguments (episode 9) | errors.Join(errs...) |
strconv.Atoi |
converts text to an int, returning an error for bad text | strconv.Atoi("two") |
*strconv.NumError |
Atoi's error type: fields Func, Num, Err |
ne.Num is "two" |
strings.LastIndex |
the index of the last occurrence of a substring, or -1 | strings.LastIndex("vada pav 1", " ") |
Summary
%vcopies text: context is added, but the original error is lost (err == ErrNotOnMenu→false).%wwraps: same message, original kept inside.errors.Unwrapopens one layer;nilwhen nothing is inside.- Layers of wrapping form a wrap chain.
errors.Is(err, target)finds a value anywhere in it;errors.As(err, &target)finds a type and fills your variable. Use them instead of==and type assertions. - A custom type joins the chain with an
Unwrap() errormethod. errors.Joinreturns many errors as one (one line each), drops nils, and returns nil when all are nil;IsandAsstill see inside.- Handle an error where you can fix it; otherwise propagate it with context. Log once, at the top.
- Opaque errors keep you free to change details; sentinels and types let callers react but become part of your API, and so does anything you wrap with
%w. - Errors for expected failures, panics for bugs.
Next episode: panic and recover: what really happens in a panic, stack unwinding, how defer and recover catch one, the common runtime panics, Must functions, panics in goroutines, and when panicking is acceptable.