Table 4 orders 3 portions of tendon meatballs, but only 2 are left. If all that comes back to the cashier is a slip saying "sorry, failed", the cashier can't do a thing. They need a slip that says which dish, how many were asked for and how many are left, so they can offer what is left. That slip then goes into an envelope marked "table 4" before it is handed over.
A slip that carries data like that is called a custom error: a type of your own that can be used as an error, because it has an Error() string method. Unlike errors.New, such a type can carry data. The envelope is the result of wrapping, and errors.Is/errors.As are how you open the envelope to read the slip inside.
error is an interface with one method
In Go, error is a built-in interface:
type error interface {
Error() string
}
Any type that has an Error() string method can be used as an error. The simplest one is made with errors.New, which returns an error holding one text:
err := errors.New("file not found")
fmt.Println(err) // file not found
fmt.Println calls Error() to get the text. Go error messages are written in lower case with no full stop at the end, because they are often joined to other messages.
Making your own error type
The stock at Bimo's till: tendon meatballs 2 portions, chicken noodles 5, iced tea 10. When an order is bigger than the stock, we want to know the dish, how many were asked for and how many are left:
type LowStockError struct {
Menu string
Asked int
Left int
}
func (e *LowStockError) Error() string {
return fmt.Sprintf("not enough %s: asked %d, left %d", e.Menu, e.Asked, e.Left)
}
var ErrNotOnMenu = errors.New("not on the menu")
var stock = map[string]int{"tendon meatballs": 2, "chicken noodles": 5, "iced tea": 10}
func takeStock(menu string, portions int) error {
left, found := stock[menu]
if !found {
return ErrNotOnMenu
}
if portions > left {
return &LowStockError{Menu: menu, Asked: portions, Left: left}
}
stock[menu] = left - portions
return nil
}
LowStockErroris an ordinary struct. Go error type names usually end inError.func (e *LowStockError) Error() stringmakes*LowStockErrorsatisfy theerrorinterface. It is a pointer receiver, so what is returned must be a pointer:&LowStockError{...}.takeStockreturns anerror, so its caller does not need to know the real type to print it or to checkerr != nil.return nilmeans it worked, and the stock goes down.
Sentinel errors: one value to compare against
ErrNotOnMenu is called a sentinel error: one error value made once at package level, which callers use to check "is this that error?". Its name usually starts with Err, with a capital letter when other packages need it.
Every call to errors.New makes a new value, even with the same text. So errors.New("not on the menu") == errors.New("not on the menu") is false. That is why a sentinel lives in one variable and is compared against that variable.
Wrapping with %w
The function above adds context, the table number, without throwing away the original error:
func order(table int, menu string, portions int) error {
err := takeStock(menu, portions)
if err != nil {
return fmt.Errorf("table %d: %w", table, err)
}
return nil
}
fmt.Errorf with the %w verb makes a new error whose text is table 4: followed by the original error's text, and keeps the original error inside it. Errors that wrap other errors form a chain: the "table 4" envelope holds the *LowStockError slip. errors.Unwrap(err) takes out one layer.
errors.Is and errors.As
func main() {
err := order(4, "tendon meatballs", 3)
fmt.Println(err)
fmt.Println("not on the menu?", errors.Is(err, ErrNotOnMenu))
var stockErr *LowStockError
if errors.As(err, &stockErr) {
fmt.Println("offer only", stockErr.Left, "portions")
}
}
$ go run stall.go
table 4: not enough tendon meatballs: asked 3, left 2
not on the menu? false
offer only 2 portions
errors.Is(err, ErrNotOnMenu)opens the chain layer by layer looking for a value equal to that sentinel. Fororder(5, "chicken soup", 1)it istrue, whileerr == ErrNotOnMenuisfalse, becauseerris the envelope, not what is inside.errors.As(err, &stockErr)looks along the chain for an error whose type is*LowStockError. When it finds one, it fillsstockErrand returnstrue, so the fields can be read:stockErr.Leftis 2.- The second argument of
errors.Asmust be the address of a variable (&stockErr), and the variable's type must be the type that has theErrormethod, here*LowStockError. - On Go 1.26 and later,
errors.AsTypedoes the same without an empty variable first:if stockErr, ok := errors.AsType[*LowStockError](err); ok { ... }also printsoffer only 2 portions. It is the default choice for new code.errors.Asis still used when the code must run on an older Go.
| Order | What prints | errors.Is |
errors.As |
|---|---|---|---|
| tendon meatballs, 3 portions | table 4: not enough tendon meatballs: asked 3, left 2 |
false | true, Left 2 |
| chicken soup, 1 portion | table 4: not on the menu |
true | false |
| chicken noodles, 2 portions | <nil> |
false | false |
%w or %v
Change %w to %v, and the printed text is still table 4: not enough tendon meatballs: asked 3, left 2. Guess before you read on: can errors.As still find the original slip?
It can't. %v only copies the error's text. The original error is not kept, so errors.As returns false, and errors.Is is false for chicken soup too. So errors.As only finds the original slip in the %w version.
Use %w when callers may inspect the original error. Use %v when you mean to hide it, for example a database error the caller has no business knowing about.
⚠️ Error chains that break or get read wrong
- Comparing with
==after wrapping.err == ErrNotOnMenuturnsfalseas soon as there is a%wlayer. Always useerrors.Is. - A pointer receiver, but a plain struct returned.
return LowStockError{...}is refused by the compiler withLowStockError does not implement error (method Error has pointer receiver). Write&LowStockError{...}. - A typed nil pointer.
var e *LowStockErrorthenreturn emakeserr != niltrueeven though it holds nil, because the interface carries the type. On the path that works, writereturn nil. - The wrong
errors.Astarget.var e LowStockErrorthenerrors.As(err, &e)makes the program panic witherrors: *target must be interface or implement error. The variable must be a*LowStockError. Witherrors.AsType, this mistake is refused at compile time:errors.AsType[LowStockError](err)fails withLowStockError does not satisfy error (method Error has pointer receiver).
TL;DR: error is an interface with one method, Error() string. errors.New("...") makes a simple error; a custom type like LowStockError{Menu, Asked, Left} with an Error() method carries data. A sentinel error like var ErrNotOnMenu = errors.New("not on the menu") is one value to compare against. fmt.Errorf("table %d: %w", table, err) wraps an error and keeps the original; %v only copies its text. errors.Is(err, ErrNotOnMenu) looks for the sentinel value along the chain, errors.As(err, &stockErr) looks for a type and fills the variable. Don't use == on a wrapped error, return &LowStockError{...} when the receiver is a pointer, and write return nil on the path that works.
⚡ An error that carries data
Write:
type LowStockError struct {
Menu string
Asked int
Left int
}
func (e *LowStockError) Error() string {
return fmt.Sprintf("not enough %s: asked %d, left %d", e.Menu, e.Asked, e.Left)
}
Meaning: Any type that has Error() string can be used as an error. The receiver is a pointer, so what you return is a pointer too: &LowStockError{...}.
⚡ A sentinel error
Write:
var ErrNotOnMenu = errors.New("not on the menu")
Meaning: One error value made once, then used to check "is this that error?". Two errors.New calls with the same text are still two different values.
⚡ Wrap with %w
Write:
return fmt.Errorf("table %d: %w", table, err)
Guess first: %w becomes %v. The text is the same. Can errors.As still find the original slip?
No. %v only copies the text, and the original error is not kept.
Meaning: %w makes a new error whose text is table 4: plus the original text, and keeps the original error inside. errors.Is looks for the sentinel value along that chain, errors.As looks for its type and fills the variable.