go · level 2 · unit 4 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
an error to add detail, then find it with .
Some errors are worth naming so other code can recognise them. var ErrSoldOut = errors.New("sold out") sits outside every function and is called a . By habit, names like this start with Err.
As an error travels back through your functions, each one can add detail. fmt.Errorf("ordering %v: %w", snack, err) puts the old error inside a new message. %w means wrap: the original stays inside, like a letter in an envelope.
errors.Is(err, ErrSoldOut) opens every envelope and gives true if the sold-out error is anywhere inside. Comparing with == only looks at the outside envelope, so it misses wrapped errors.
package main
import "errors"
import "fmt"
var ErrSoldOut = errors.New("sold out")
func order(snack string, stock map[string]int) error {
if stock[snack] == 0 {
return fmt.Errorf("ordering %v: %w", snack, ErrSoldOut)
}
return nil
}
func main() {
stock := map[string]int{"crisps": 0, "apples": 5}
err := order("crisps", stock)
fmt.Println(err)
fmt.Println(errors.Is(err, ErrSoldOut), err == ErrSoldOut)
} Only %w wraps, so %v would copy the message as text and lose the error inside.
guess first
Two envelopes deep. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
package main
import "errors"
import "fmt"
var ErrNoSeats = errors.New("no seats left")
func book(film string) error {
return fmt.Errorf("booking %v: %w", film, ErrNoSeats)
}
func plan(film string) error {
err := book(film)
if err != nil {
return fmt.Errorf("planning Friday: %w", err)
}
return nil
}
func main() {
fmt.Println(plan("Paddington"))
}
your turn
Your turn. Weigh the holiday suitcase.
Wrap the sentinel error with the verb that keeps it findable. Pack a bag heavier than 20 kg, then ask errors.Is about the right sentinel error.
output
press run to see what happens
fix it
The kitchen is locked, but nobody fetches the key. Fix it!
output
press run to see what happens
- The message mentions the locked door, yet
errors.Issays no. Look at how line 6 builds the error. %vcopies the message as plain text. Only one verb keeps the original error inside.- Change the second %v on line 6 to %w, then run.
nailed it
your errors carry their whole story. :D
- A sentinel error is a named error made once with
errors.New. %winfmt.Errorfwraps an error inside a new message.errors.Isfinds a sentinel error through every layer.
new words in your collection
- sentinel error
- wrap
- errors.Is
This lesson isn’t saved. A free account remembers every lesson you finish.