×

go · level 2 · unit 4 · lesson 3

  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

Make your own to carry the details.

A sentinel error says what went wrong, but not the details. How much money was missing? Which box on the form was empty? An error type can carry those details, because error is an interface: any type with an Error() string method satisfies it.

type ShortError struct { Need int } plus a func (e ShortError) Error() string method makes a ready-to-use error type. You can hand back ShortError{Need: 12} anywhere an error is expected.

To get the details back, declare a box of your type and hand its address to : errors.As(err, &short). If one is found, even wrapped inside, it gives true and fills short in.

package main
import "errors"
import "fmt"
type ShortError struct {
	Need int
}
func (e ShortError) Error() string {
	return fmt.Sprintf("not enough money, need £%v more", e.Need)
}
func main() {
	var err error = ShortError{Need: 12}
	err = fmt.Errorf("buying the game: %w", err)
	fmt.Println(err)
	var short ShortError
	if errors.As(err, &short) {
		fmt.Println("Save up another", short.Need, "pounds")
	}
}

Use errors.Is to ask whether it is that exact error, and errors.As to ask for one of your error types.