×

go · level 2 · unit 4 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.