33. Errors in depth

You have been handling errors since Chapter 21. A function returns an error as its last value, the caller checks if err != nil on the next line, and errors.New or fmt.Errorf makes a new one. Chapter 29 showed that error is an interface, so your own types can be errors. Chapter 31 used errors.Is(err, os.ErrNotExist) without explaining it, and Chapter 32 sent messages to standard error and ended with an exit code.

That is enough for small programs. In a tool that reads files, a few questions come up again and again:

  • The error says invalid syntax. In which file, on which line?
  • How do you add those details without losing the original error?
  • How does the caller find out what kind of error it got, to decide what to do?
  • Which function should print the error, and which should only pass it on?

This chapter answers them, and ends with the tidy way to turn an error into a message and an exit code that Chapter 32 promised.

An error should say what and where

Here is a small scores file, exercises/33/bad-scores.txt. Each line has a name and a number of points, and line 3 has a mistake:

Keiko 12
Arif 9
Budi ten
Sari 15

exercises/33/01-add-context.go adds up the points twice. totalBare passes the error from strconv.Atoi straight back, as you have done so far:

points, err := strconv.Atoi(fields[1])
if err != nil {
    return 0, err
}

totalWithContext counts the lines, and puts the file name and the line number in front of the error:

points, err := strconv.Atoi(fields[1])
if err != nil {
    return 0, fmt.Errorf("%s:%d: %w", name, number, err)
}

main runs both on the bad file. Output:

Bare:         strconv.Atoi: parsing "ten": invalid syntax
With context: exercises/33/bad-scores.txt:3: strconv.Atoi: parsing "ten": invalid syntax

The first message is true, but useless in a file of a thousand lines. The second says exactly where to look. name:line: in front is the form the Go compiler uses for its own errors, as Chapter 10 showed, and many tools copy it.

%w is a verb that only fmt.Errorf has. In the message it prints the error like %v would. What else it does is the next section.

strconv.Atoi itself already follows the rule: it says what it was doing (parsing) and with which text ("ten"). Go programmers write error messages in a certain way, because messages get joined together like this one:

  • Say what was being done, and with which value: parsing "ten", open notes.txt.
  • Add only what the error does not say yet. The error from os.Open already holds the file name, so fmt.Errorf("open %s: %w", name, err) would print the name twice.
  • Start with a small letter and leave out the full stop at the end. The message is often the middle of a longer one, and reading settings: Open failed.: ... reads badly.

Both functions read fields[1] without checking that the line has two fields. A line with only a name would stop the program with index out of range. The full parser later in this chapter checks.

Wrapping: an error inside an error

fmt.Errorf with %v makes a new error out of the old one's text. With %w it wraps the old error: the new error holds the old one inside it, like a letter in an envelope with a note written on the outside. The text looks the same, but the original is still there for anyone who wants to look. This is exercises/33/02-wrap.go:

func readWithW(name string) error {
    _, err := os.ReadFile(name)
    if err != nil {
        return fmt.Errorf("reading settings: %w", err)
    }
    return nil
}

readWithV is the same with %v. main calls both on a file that does not exist:

errW := readWithW("no-such-file.txt")
errV := readWithV("no-such-file.txt")

fmt.Println(errW)
fmt.Println(errV)

fmt.Printf("readWithW still holds ErrNotExist: %v\n", errors.Is(errW, os.ErrNotExist))
fmt.Printf("readWithV still holds ErrNotExist: %v\n", errors.Is(errV, os.ErrNotExist))

fmt.Println("Unwrapped once:", errors.Unwrap(errW))

Output on Windows:

reading settings: open no-such-file.txt: The system cannot find the file specified.
reading settings: open no-such-file.txt: The system cannot find the file specified.
readWithW still holds ErrNotExist: true
readWithV still holds ErrNotExist: false
Unwrapped once: open no-such-file.txt: The system cannot find the file specified.

The two messages are the same, but only the wrapped error still knows that the file does not exist. The %v version is just text now: a caller that wants to treat a missing file as "use the defaults", as in Chapter 31, can no longer tell.

errors.Unwrap takes off one envelope and gives back the error inside, or nil if there is none. You will rarely call it yourself, but it shows what errors.Is does: it compares the error with the target, and if they are not the same, unwraps and compares again, all the way down.

This is the explanation Chapter 31 promised. Even without your wrapping, the error from os.ReadFile is already an envelope. Its type is *fs.PathError, from the io/fs package, and it holds three things: the operation (open), the path (no-such-file.txt), and the error from the operating system. That last one is the "does not exist" error. So err == os.ErrNotExist is false, because the outside envelope is a PathError, while errors.Is opens it and finds the match inside.

Always compare errors with errors.Is, not ==. == only looks at the outside envelope, so it stops working as soon as someone, perhaps you, adds a wrap.

Use %w when you add context to an error you pass on. Use %v only when you want to hide the original on purpose, so that callers do not depend on it.

Sentinel errors

os.ErrNotExist is a sentinel error: one error value, made once, that stands for one kind of problem. Callers check for it with errors.Is. You already know another from Chapter 21 without its name: when ReadString runs out of input, the error it returns is io.EOF ("end of file").

Your own sentinel errors are package-level variables made with errors.New. This is exercises/33/03-sentinel.go:

var errNoName = errors.New("no name given")
var errNotFound = errors.New("no such player")

// findScore returns the score of the named player.
func findScore(scores map[string]int, name string) (int, error) {
    if name == "" {
        return 0, errNoName
    }
    score, ok := scores[name]
    if !ok {
        return 0, fmt.Errorf("%w: %s", errNotFound, name)
    }
    return score, nil
}

errNoName is returned as it is. errNotFound is wrapped, so that the message also says which name was missing. The %w can be anywhere in the format, here at the start. main asks each player and picks a reply with a switch from Chapter 16:

for _, name := range []string{"Keiko", "Budi", ""} {
    score, err := findScore(scores, name)
    switch {
    case errors.Is(err, errNotFound):
        fmt.Println("Not on the board:", err)
    case errors.Is(err, errNoName):
        fmt.Println("Type a name first.")
    case err != nil:
        fmt.Println("Error:", err)
    default:
        fmt.Printf("%s has %d points.\n", name, score)
    }
}

Output:

Keiko has 12 points.
Not on the board: no such player: Budi
Type a name first.

errors.Is(nil, errNotFound) is false, so a nil error falls through to default. The case err != nil line catches any other error, in case findScore one day returns a new kind. Without it, that error would be treated as success.

Sentinel names start with err, or with Err when another package should see them, as Chapter 25 explained for all names: os.ErrNotExist, io.EOF. The caller decides with errors.Is, never by reading the message. Messages are for people, and you should be free to change one without breaking a program that checks for it.

In exercises/33/03-sentinel.go, add a sentinel errBanned and a check in findScore that returns it for the name "Cheater". Give it its own case in main.

An error type of your own

A sentinel says what kind of problem it was, but carries no details a program can use. The message exercises/33/bad-scores.txt:3: ... holds a file and a line, but only as text. When the caller needs the details as values, make an error type, as Chapter 29 did with levelError. This is exercises/33/04-custom-type.go:

// parseError reports a line in a scores file that could not be read.
type parseError struct {
    file    string
    line    int
    problem string
}

func (e parseError) Error() string {
    return fmt.Sprintf("%s:%d: %s", e.file, e.line, e.problem)
}

parseScores reads the file into a slice of score structs. Every bad line returns a parseError. The first check fixes the index out of range problem from the start of the chapter:

fields := strings.Fields(line)
if len(fields) != 2 {
    return nil, parseError{file: name, line: number, problem: "want a name and a score"}
}
points, err := strconv.Atoi(fields[1])
if err != nil {
    problem := fmt.Sprintf("score %q is not a whole number", fields[1])
    return nil, parseError{file: name, line: number, problem: problem}
}
scores = append(scores, score{name: fields[0], points: points})

The problem now says score "ten" is not a whole number instead of passing on strconv.Atoi: parsing "ten": invalid syntax. That message is about Go functions, while the person reading it cares about their file. When an error means "the input is wrong", a message in the input's own words helps them fix it.

To get the details back, the caller uses errors.As:

func report(name string) {
    scores, err := parseScores(name)
    if err != nil {
        fmt.Println("Error:", err)

        var pe parseError
        if errors.As(err, &pe) {
            fmt.Printf("Open %s and fix line %d.\n", pe.file, pe.line)
        }
        return
    }
    ...
}

main calls report for a good file, the bad file, and a missing one. Output on Windows:

exercises/33/scores.txt: 3 players, 36 points
Error: exercises/33/bad-scores.txt:3: score "ten" is not a whole number
Open exercises/33/bad-scores.txt and fix line 3.
Error: open exercises/33/no-such-file.txt: The system cannot find the file specified.

errors.As is to the type assertion of Chapter 29 what errors.Is is to ==. It looks through every layer of wrapping for an error of the type of pe. If it finds one, it copies it into pe and returns true. That is why it takes &pe, a pointer: as Chapter 27 showed, a function needs a pointer to fill in your variable. For the missing file, no layer is a parseError, so it returns false, and only the Error: line prints.

The type of the variable must match the type that was returned exactly. parseScores returns parseError values, so pe is a parseError. Many error types in the standard library are returned as pointers, such as *fs.PathError, and then the variable must be a pointer too: var pathErr *fs.PathError.

In the report function of exercises/33/04-custom-type.go, add a second check with var pathErr *fs.PathError and errors.As(err, &pathErr), and print pathErr.Path. Add "io/fs" to the imports. Which of the three files reaches it?

When your error type holds another error, for example the one from strconv.Atoi, give it a method Unwrap() error that returns that error. errors.Is and errors.As then look inside your type too, as they do for *fs.PathError.

Which to use? Start with fmt.Errorf and %w. Add a sentinel when a caller needs to react to one kind of problem. Make an error type when a caller needs the details as values.

Several problems at once

A function that stops at the first problem makes the user fix one thing, run again, find the next, and run again. When checking a form or a whole file, it is kinder to report everything at once. errors.Join combines several errors into one. This is exercises/33/05-join.go:

var errTooLong = errors.New("name is too long")

// checkPlayer returns every problem with a new player, or nil if there are none.
func checkPlayer(name string, points int) error {
    var problems []error
    if name == "" {
        problems = append(problems, errors.New("name is empty"))
    }
    if len(name) > 10 {
        problems = append(problems, fmt.Errorf("%w: %q has %d letters, the most is 10", errTooLong, name, len(name)))
    }
    if points < 0 {
        problems = append(problems, fmt.Errorf("points %d is below 0", points))
    }
    return errors.Join(problems...)
}

problems... spreads the slice into separate arguments, as with append in Chapter 22. main checks a good player and a bad one:

fmt.Println("Keiko, 12:", checkPlayer("Keiko", 12))

err := checkPlayer("Bartholomew", -5)
fmt.Println("Bartholomew, -5:")
fmt.Println(err)
fmt.Println("Too long?", errors.Is(err, errTooLong))

Output:

Keiko, 12: <nil>
Bartholomew, -5:
name is too long: "Bartholomew" has 11 letters, the most is 10
points -5 is below 0
Too long? true
  • With no problems, the slice is empty and errors.Join returns nil. So the function returns nil when all is well, as an error-returning function should.
  • The joined error's message is the messages of its parts, one per line.
  • errors.Is and errors.As look inside every part.

Return, handle, or exit

Every time you write if err != nil, you choose one of three things.

Where you are What to do
A function that cannot fix the problem Return it, wrapped with what this function knows and the caller does not.
A function that knows what the problem means Handle it: use a default, skip the line, ask again, choose a reply.
main Exit: print one clear message to standard error, and end with a code that is not 0.

Most functions are in the first row. parseScores cannot know whether a bad line should stop the program or just be reported, so it returns the error with the file and line added. loadName in Chapter 31 was in the second row: a missing file means "use the defaults", and it says so. Only main knows that this is a command-line tool, with a standard error and an exit code, so only main exits.

Two habits follow from the table:

  • Handle an error once. A function that prints an error and returns it makes the message appear twice, once here and once wherever the caller prints it. Either deal with it, or pass it on.

    if err != nil {
      fmt.Println("Error:", err) // printed here...
      return err                 // ...and again by the caller
    }
  • Do not throw errors away. _ in place of err hides every problem. Use it only when you are sure the error cannot matter, and say why in a comment.

You have seen Go stop a program with panic, for an index out of range in Chapter 22 and a nil pointer in Chapter 27. A panic means a bug: the program did something that should never happen. A missing file or a typo in the input is not a bug. It is an ordinary error, and it is returned, not panicked.

A tool that exits cleanly

Chapter 32 warned that os.Exit skips deferred calls, and said to call it only in main, after the work is done. The tidy way to arrange that is to move all the work out of main into a function, usually called run, that returns an error. main then does just one job: it turns that error into a message and an exit code. This is exercises/33/06-run.go:

var errUsage = errors.New("wrong usage")

func main() {
    err := run(os.Args[1:])
    if errors.Is(err, errUsage) {
        fmt.Fprintln(os.Stderr, "usage: scores FILE")
        os.Exit(2)
    }
    if err != nil {
        fmt.Fprintln(os.Stderr, "scores:", err)
        os.Exit(1)
    }
}

// run does the whole job, and returns an error instead of exiting.
func run(args []string) error {
    if len(args) != 1 {
        return errUsage
    }

    scores, err := parseScores(args[0])
    if err != nil {
        return err
    }

    total := 0
    for _, s := range scores {
        fmt.Printf("%-8s %3d\n", s.name, s.points)
        total += s.points
    }
    fmt.Printf("%-8s %3d\n", "Total", total)
    return nil
}

parseScores and parseError are the ones from 04-custom-type.go. Look at what this arrangement gives you:

  • Deferred calls always run. By the time main calls os.Exit, run has returned, and so has every function it called. Every deferred Close has already happened.
  • One place decides the exit code. A sentinel, errUsage, tells wrong usage (code 2) apart from a failure (code 1), with the table from Chapter 32.
  • run returns err as it is. The error from parseScores already says the file and line, and the one from os.Open already says the file. Wrapping them again would add nothing.
  • run is easy to test. It takes the arguments as a slice, so a test can call it with any arguments, without a terminal. Chapter 34 is about tests.

The smallest form of the pattern has only the second if: main calls run, prints any error to standard error with the tool's name in front, and calls os.Exit(1). Add the check for wrong usage when the tool needs a second exit code. The To-do Tool at the end of this part does, with a small error type and errors.As in place of the sentinel, because each of its usage mistakes has its own message.

Three runs:

go run exercises/33/06-run.go exercises/33/scores.txt
Keiko     12
Arif       9
Sari      15
Total     36

go run exercises/33/06-run.go exercises/33/bad-scores.txt
scores: exercises/33/bad-scores.txt:3: score "ten" is not a whole number
exit status 1

go run exercises/33/06-run.go
usage: scores FILE
exit status 2

Build it, and the exit code is the program's own:

go build -o scores.exe exercises/33/06-run.go
.\scores.exe nothing.txt
scores: open nothing.txt: The system cannot find the file specified.

$LASTEXITCODE
1

Every message starts with the tool's name, says what went wrong and where, and goes to standard error. That is all a user needs to fix the problem.

Give exercises/33/06-run.go a second sentinel, errNoScores, that run returns when the file has no scores in it. Make main print scores: the file is empty for it and exit with code 1. Try it on an empty file.

Homework

Homework starters are in exercises/33/homework/, with the files they read. Each starter runs as it is, with a placeholder.

Problem 1 — Errors that say where

Open exercises/33/homework/01-sum-file.go. Write sumFile, which adds up a file with one whole number per line. When a line is not a number, wrap the error from strconv.Atoi with the file name and the line number, using %w. main is finished. It checks for strconv.ErrSyntax, a sentinel that strconv wraps inside its own errors, and that check only works if your wrap keeps the original.

Problem 2 — Sentinel errors

Open exercises/33/homework/02-library.go. Declare two sentinel errors, errNoSuchBook and errAlreadyOut, and write borrow, which returns them. Wrap errNoSuchBook with the title. In main, use errors.Is to print a friendly line for each.

Problem 3 — An error type of your own

Open exercises/33/homework/03-settings.go. Finish loadSettings, which reads key = value lines. A missing file is not an error. A line with no = returns a lineError. Write its Error method, and in main, use errors.As to print the line number.

Challenge — A score file checker

Open exercises/33/homework/04-check-scores.go. Write check FILE..., which checks scores files and reports every bad line of every file, collected with errors.Join. A file it cannot open is one more problem, not the end. Use the run pattern, and exit with 0, 1 or 2. Try it on exercises/33/homework/messy-scores.txt.

Stuck or done? Open the homework solutions page.