Custom Errors

In the last lesson, every error was made on the spot with errors.New or fmt.Errorf. The caller could print the message, but it could not easily tell which problem happened. Go gives you two ways to fix that: sentinel errors and your own error types.

Sentinel errors

A sentinel error is one error value that you create once, store in a package-level variable and return every time the same problem happens. By convention its name starts with Err.

package main

import (
	"errors"
	"fmt"
)

var ErrNotFound = errors.New("user not found")

var ages = map[string]int{"alice": 30, "bob": 25}

func findAge(name string) (int, error) {
	age, ok := ages[name]
	if !ok {
		return 0, ErrNotFound
	}
	return age, nil
}

func main() {
	_, err := findAge("zoe")
	if err == ErrNotFound {
		fmt.Println("no such user")
	}
	fmt.Println(errors.Is(err, ErrNotFound))
}

Output:

no such user
true

The caller compares err with ErrNotFound using ==. The function errors.Is gives the same answer here. The difference shows up when an error is wrapped inside another one, which the next lesson covers. For now, both work.

The comparison only works because the same value is returned each time. Every call to errors.New makes a new, different error, even when the text is the same:

a := errors.New("user not found")
b := errors.New("user not found")
fmt.Println(a == b)

Output:

false

So never compare errors by making a new one with the same text. Compare with the shared variable.

Your own error type

A sentinel says which problem happened, but it cannot carry details. Sometimes the caller needs numbers, like how far a value was out of range.

error is an interface with one method, Error() string. Any type that has this method is an error. So you can write a struct with the fields you need and give it an Error method:

package main

import (
	"errors"
	"fmt"
)

type RangeError struct {
	Value int
	Max   int
}

func (e RangeError) Error() string {
	return fmt.Sprintf("%d is more than %d",
		e.Value, e.Max)
}

func setVolume(level int) error {
	if level > 10 {
		return RangeError{Value: level, Max: 10}
	}
	return nil
}

func main() {
	err := setVolume(15)
	fmt.Println(err)

	var re RangeError
	if errors.As(err, &re) {
		fmt.Println("too high by", re.Value-re.Max)
	}
}

Output:

15 is more than 10
too high by 5

fmt.Sprintf, from the Formatted Output lesson, returns the text instead of printing it. fmt.Println(err) calls the Error method, so it prints the message.

setVolume returns a RangeError as a plain error. To read its fields again, the caller uses errors.As. It checks whether err holds a RangeError. If it does, it copies that value into re and returns true. Then re.Value and re.Max are ready to use.

A common mistake

errors.As must get a pointer, &re, so that it can fill in re. This is the same reason fmt.Scan needs &. If you forget the &, the program still compiles, but it stops when it runs:

package main

import (
	"errors"
	"fmt"
)

type RangeError struct {
	Value int
	Max   int
}

func (e RangeError) Error() string {
	return fmt.Sprintf("%d is more than %d",
		e.Value, e.Max)
}

func main() {
	var err error = RangeError{15, 10}
	var re RangeError
	fmt.Println(errors.As(err, re))
}

Output:

panic: errors: target must be a non-nil pointer

A panic stops the program with a message. The Panic and Recover lesson explains panics.

Use a sentinel error when the caller only needs to know which problem happened. Write an error type when the caller also needs details.

In the exercise, a shop returns a StockError when it does not have enough items. Finish its Error method, return it from buy, and get it back in main with errors.As.