33. Errors in depth — Homework solutions
The .go solution files are in
exercises/33/homework/solutions/. Run each one from
go-work, as usual.
Problem 1 — Errors that say where
Problem. Add up a file of numbers, and make a bad line report its file and line number without losing the original error.
How to think about it. The reading loop is
printNumbered from Chapter 31, with a total instead of
printing. The line counter goes up at the top of every round, so it is
right even when the round fails. The file name is the parameter, and the
line number is the counter: both are things sumFile knows
and strconv.Atoi does not, which is exactly what to add.
Use %w, because main looks inside the
error.
Worked solution.
func sumFile(name string) (int, error) {
f, err := os.Open(name)
if err != nil {
return 0, err
}
defer f.Close()
total := 0
number := 0
scanner := bufio.NewScanner(f)
for scanner.Scan() {
number++
n, err := strconv.Atoi(strings.TrimSpace(scanner.Text()))
if err != nil {
return 0, fmt.Errorf("%s:%d: %w", name, number, err)
}
total += n
}
return total, scanner.Err()
}Output:
exercises/33/homework/numbers.txt: total 108
Error: exercises/33/homework/bad-numbers.txt:3: strconv.Atoi: parsing "thirty": invalid syntax
(a line is not a whole number)
The error from os.Open is returned as it is, because it
already names the file.
Common mistakes.
- Writing
%vinstead of%w. The message is the same, but the last line of the output is missing:errors.Iscan no longer findstrconv.ErrSyntax. - Counting lines only after a successful
Atoi. The bad line is then reported as line 2, one too few, because the counter missed the line that failed. - Adding the file name to the error from
os.Opentoo. It prints the name twice:nothing.txt: open nothing.txt: ....
Problem 2 — Sentinel errors
Problem. Give borrow two kinds of
failure that main can tell apart.
How to think about it. Each kind of failure is one
sentinel, declared once at the top with errors.New. The map
lookup with , ok from Chapter 23 tells a missing title
apart from a book that is out: ok says whether the title is
there, and the value says whether it is out. Only the missing title
needs the extra detail, so only that one is wrapped. In
main, a switch with errors.Is
picks a reply, and the err != nil case catches anything
else.
Worked solution.
var errNoSuchBook = errors.New("no such book")
var errAlreadyOut = errors.New("book is already out")
func borrow(library map[string]bool, title string) error {
out, ok := library[title]
if !ok {
return fmt.Errorf("%w: %s", errNoSuchBook, title)
}
if out {
return errAlreadyOut
}
library[title] = true
return nil
}
func main() {
library := map[string]bool{"Dune": false, "Emma": false, "Ulysses": true}
for _, title := range []string{"Dune", "Dune", "Hamlet", "Ulysses"} {
err := borrow(library, title)
switch {
case errors.Is(err, errNoSuchBook):
fmt.Println("We do not have that one:", err)
case errors.Is(err, errAlreadyOut):
fmt.Printf("Sorry, %s is out. Try again next week.\n", title)
case err != nil:
fmt.Println("Error:", err)
default:
fmt.Printf("You borrowed %s.\n", title)
}
}
}Output:
You borrowed Dune.
Sorry, Dune is out. Try again next week.
We do not have that one: no such book: Hamlet
Sorry, Ulysses is out. Try again next week.
The second Dune fails because the first call changed the
map. A map is shared, not copied, when passed to a function, as Chapter
23 showed.
Common mistakes.
- Checking with
err == errNoSuchBook. It isfalseforHamlet, because the error that came back is the wrapper, not the sentinel. Useerrors.Is. - Making the sentinel inside
borrow, withreturn errors.New("no such book"). Each call then makes a new, different error, anderrors.Isnever matches. A sentinel is made once, outside any function. - Using
library[title]without, ok. A missing title givesfalse, the same as a book on the shelf, soHamletis "borrowed" and added to the map.
Problem 3 — An error type of your own
Problem. Read a settings file. A bad line returns an error that carries its line number as a value.
How to think about it. Three kinds of line: skip
(empty or #), bad (no =), and good.
strings.Index from Chapter 14 finds the = and
gives -1 when there is none. The parts before and after it
are line[:i] and line[i+1:], with the spaces
trimmed. The missing file is handled straight after
os.Open, as in Chapter 31, and the general check comes
after it. Error builds the message from the fields, and
errors.As in main gets the fields back.
Worked solution.
func (e lineError) Error() string {
return fmt.Sprintf("%s:%d: %q has no \"=\"", e.file, e.line, e.text)
}
func loadSettings(name string) (map[string]string, error) {
settings := map[string]string{}
f, err := os.Open(name)
if errors.Is(err, os.ErrNotExist) {
return settings, nil
}
if err != nil {
return nil, err
}
defer f.Close()
number := 0
scanner := bufio.NewScanner(f)
for scanner.Scan() {
number++
line := strings.TrimSpace(scanner.Text())
if line == "" || strings.HasPrefix(line, "#") {
continue
}
i := strings.Index(line, "=")
if i < 0 {
return nil, lineError{file: name, line: number, text: line}
}
key := strings.TrimSpace(line[:i])
value := strings.TrimSpace(line[i+1:])
settings[key] = value
}
return settings, scanner.Err()
}And in main:
if err != nil {
fmt.Println("Error:", err)
var le lineError
if errors.As(err, &le) {
fmt.Printf("Look at line %d.\n", le.line)
}
continue
}Output:
Error: exercises/33/homework/settings.txt:4: "sound off" has no "="
Look at line 4.
exercises/33/homework/no-settings.txt: 0 settings
Change line 4 of settings.txt to
sound = off, and the first line of the output becomes
exercises/33/homework/settings.txt: 4 settings.
\" in the format string is a double quote inside a Go
string, as in Chapter 12.
Common mistakes.
- Writing
errors.As(err, le)without the&. Go stops the program with a panic, becauseerrors.Asneeds a pointer to fill in. - Declaring
var le *lineErrorwhileloadSettingsreturns alineErrorvalue. The types do not match, soerrors.Asreturnsfalseand the line number never prints. - Putting the
os.ErrNotExistcheck afterif err != nil. The general check catches the missing file first and returns it as an error.
Challenge — A score file checker
Problem. Check several scores files, and report every bad line of every file, with the right exit code.
How to think about it. Split the job into layers, each with one task:
checkLinelooks at one line and returns what is wrong with it, as text, or"". It knows nothing about files.checkFileopens one file, adds the file name and line number to each problem as alineError, and joins them. It returnsnilfor a good file.runchecks every file, printsokfor the good ones, and joins the errors of the bad ones. A file that cannot be opened is one more error in the list, so the loop carries on.mainturns the result into a message and an exit code, as in the chapter.
errors.Join appears twice: the problems of one file,
then the files. The message of the result is every problem, one per
line.
Worked solution.
var errUsage = errors.New("wrong usage")
// lineError reports one bad line in a scores file.
type lineError struct {
file string
line int
problem string
}
func (e lineError) Error() string {
return fmt.Sprintf("%s:%d: %s", e.file, e.line, e.problem)
}
func main() {
err := run(os.Args[1:])
if errors.Is(err, errUsage) {
fmt.Fprintln(os.Stderr, "usage: check FILE...")
os.Exit(2)
}
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func run(args []string) error {
if len(args) == 0 {
return errUsage
}
var problems []error
for _, name := range args {
err := checkFile(name)
if err != nil {
problems = append(problems, err)
continue
}
fmt.Printf("%s: ok\n", name)
}
return errors.Join(problems...)
}
// checkFile returns every problem in one file, or nil if it is good.
func checkFile(name string) error {
f, err := os.Open(name)
if err != nil {
return err
}
defer f.Close()
var problems []error
number := 0
scanner := bufio.NewScanner(f)
for scanner.Scan() {
number++
line := strings.TrimSpace(scanner.Text())
if line == "" {
continue
}
problem := checkLine(line)
if problem != "" {
problems = append(problems, lineError{file: name, line: number, problem: problem})
}
}
err = scanner.Err()
if err != nil {
problems = append(problems, fmt.Errorf("%s: %w", name, err))
}
return errors.Join(problems...)
}
// checkLine returns what is wrong with one line, or "" if nothing is.
func checkLine(line string) string {
fields := strings.Fields(line)
if len(fields) != 2 {
return "want a name and a score"
}
points, err := strconv.Atoi(fields[1])
if err != nil {
return fmt.Sprintf("score %q is not a whole number", fields[1])
}
if points < 0 {
return fmt.Sprintf("score %d is below 0", points)
}
return ""
}Output on Windows:
go run exercises/33/homework/solutions/04-check-scores.go exercises/33/scores.txt exercises/33/homework/messy-scores.txt nothing.txt
exercises/33/scores.txt: ok
exercises/33/homework/messy-scores.txt:2: want a name and a score
exercises/33/homework/messy-scores.txt:3: score "ten" is not a whole number
exercises/33/homework/messy-scores.txt:6: score -3 is below 0
open nothing.txt: The system cannot find the file specified.
exit status 1
go run exercises/33/homework/solutions/04-check-scores.go exercises/33/scores.txt
exercises/33/scores.txt: ok
go run exercises/33/homework/solutions/04-check-scores.go
usage: check FILE...
exit status 2
Line 4 of messy-scores.txt is empty, so it is skipped,
and the line numbers still match the file because the counter goes up
before the continue.
The error from scanner.Err() is wrapped with the file
name, because the scanner's error does not say which file it was
reading. The error from os.Open already does.
Common mistakes.
- Returning at the first bad line. That is
parseScoresfrom the chapter, and it reports only line 2. Collect the problems and join them at the end. - Calling
os.Exit(1)inside the loop inrunwhen a file is missing. The files after it are never checked. - Printing each problem in
checkFileand also returning it. Every problem then appears twice. Handle an error once.
Done?
Your errors now say what went wrong and where, keep the original
inside, and reach main as one clear message and an exit
code. The next chapter checks your code automatically:
go test runs small test functions, and tells you the moment
a change breaks something that used to work.