Skip to content

Recognize a Known Error

The Course
•
25 min study

In the beginner course an error was something to print. The queue needs more: when done 9 names a task that doesn't exist, the program reports it and carries on, but a different caller might want to react differently to "missing" than to "already done". To react, code has to recognise which error it got, and the message text is a poor way to do that: someone rewords it, or adds context to it, and every comparison breaks.

A sentinel is a shared error value for a condition callers can recognise. Define it once, at package level, with errors.New, and return that same value wherever the condition happens. Two calls to errors.New with the same text create two different errors, so callers recognise the shared value with errors.Is, never by comparing text.

Predict and run

Do the two errors match by identity?

Predict, then run Go
package main

import (
	"errors"
	"fmt"
)

var errMissing = errors.New("task missing")

func main() {
	fmt.Println(errors.Is(errMissing, errMissing))
	fmt.Println(errors.Is(errors.New("task missing"), errMissing))
}
Check your prediction
Text
true
false

Change the second message. Did the rule change?

Why not compare the text?

Comparing text looks simpler, and it works until the day someone improves the message:

Text breaks, identity doesn't Go
package main

import (
	"errors"
	"fmt"
)

var errMissing = errors.New("task not found")

func find(id int) error {
	return errMissing
}

func main() {
	err := find(9)
	fmt.Println(err.Error() == "task missing")
	fmt.Println(errors.Is(err, errMissing))
}
Text
false
true

The message was changed from task missing to task not found, and the text comparison now says the error isn't a missing task. errors.Is still says it is, because it compares the error value, which didn't change. The next lesson shows the other way text comparison breaks: adding context to the message.

Practice

Exercise

Your turn

A stock room answers requests for items. Write take(stock map[string]int, item string, n int) error, which removes n of an item from the map. It returns the sentinel errUnknown for an item that isn't stocked, and errShort when there are fewer than n, without changing the map in either case. In main, try the starter's three requests and print a different line for each kind of failure, chosen with errors.Is. The output should be:

Text
took 2 tape
not stocked: glue
only 1 left: pens
tape=3 pens=1
Your working space Go
package main

import (
	"fmt"
)

type request struct {
	item string
	n    int
}

func main() {
	stock := map[string]int{"tape": 5, "pens": 1}
	requests := []request{{"tape", 2}, {"glue", 1}, {"pens", 3}}
	fmt.Println(stock, requests)
}
Hint 1: the idea

Two sentinels, declared once with var at the top of the file, and take returns one of them on each failure path. The caller asks errors.Is(err, errUnknown) first and errors.Is(err, errShort) second, and prints its own message for each.

Hint 2: a first step

Declare var errUnknown = errors.New("unknown item") and var errShort = errors.New("not enough stock"). In take, use the comma-ok lookup to find unknown items first, and return before changing the map.

Worked solution
Run the solution Go
package main

import (
	"errors"
	"fmt"
)

var (
	errUnknown = errors.New("unknown item")
	errShort   = errors.New("not enough stock")
)

func take(stock map[string]int, item string, n int) error {
	have, ok := stock[item]
	if !ok {
		return errUnknown
	}
	if have < n {
		return errShort
	}
	stock[item] = have - n
	return nil
}

type request struct {
	item string
	n    int
}

func main() {
	stock := map[string]int{"tape": 5, "pens": 1}
	requests := []request{{"tape", 2}, {"glue", 1}, {"pens", 3}}
	for _, r := range requests {
		err := take(stock, r.item, r.n)
		switch {
		case err == nil:
			fmt.Println("took", r.n, r.item)
		case errors.Is(err, errUnknown):
			fmt.Println("not stocked:", r.item)
		case errors.Is(err, errShort):
			fmt.Printf("only %d left: %s\n", stock[r.item], r.item)
		}
	}
	fmt.Printf("tape=%d pens=%d\n", stock["tape"], stock["pens"])
}
Text
took 2 tape
not stocked: glue
only 1 left: pens
tape=3 pens=1

The caller's messages are its own, and take's messages can change without breaking them. var ( ... ) declares several package-level variables in one block. The switch with no value after it runs the first case whose condition is true, like an if/else if chain; the command-parsing lesson later today looks at switch properly. An if/else if chain is a fine answer here too.

Was this article helpful?

Your response is saved on this device.