Go Playbook

Course › Week 2 · Methods, interfaces, errors, tests › Day 3 · lesson 10 of 42 · 20 min reading + 60 min practice

Wrapping and inspecting errors

Add context with %w, check for a known error with errors.Is, and read a custom error with errors.As.

%werrors.Iserrors.Assentinel errorscustom error types

On this page
  1. Wrapping
  2. Known errors
  3. Errors with data
  4. Coming from PHP
  5. Practice
  6. Remember

An error that travels up through four functions should arrive with four pieces of context: what each function was trying to do. Go builds that as a chain: each function wraps the error it received in a new one that adds its own words, and the original stays inside.

Today: wrapping with %w, checking for a known error anywhere in the chain with errors.Is, error types that carry data and errors.As, and one trap with nil.

Wrapping

1. %w wraps an error

fmt.Errorf with the verb %w makes a new error whose message includes the old one, and which keeps the old one inside.

main.go
package main

import (
	"fmt"
	"os"
	"strconv"
)

func parseNights(text string) (int, error) {
	nights, err := strconv.Atoi(text)
	if err != nil {
		return 0, fmt.Errorf("parsing nights: %w", err)
	}
	return nights, nil
}

func loadBooking(row []string) error {
	if _, err := parseNights(row[1]); err != nil {
		return fmt.Errorf("booking %s: %w", row[0], err)
	}
	return nil
}

func main() {
	if err := loadBooking([]string{"1042", "three"}); err != nil {
		fmt.Fprintln(os.Stderr, "import failed:", err)
		os.Exit(1)
	}
}
$ go run .
import failed: booking 1042: parsing nights: strconv.Atoi: parsing "three": invalid syntax
exit status 1

Read the message from left to right and it is the call stack, from the outside in: the import, the booking, the field, the original cause. Each function added only what it knew. Compare it with the errors lesson, where the first message replaced strconv’s error and lost the detail.

The style that makes chains readable: the wrapping text says what this function was doing (“parsing nights”), in lowercase, with no “failed to” and no “error:”. Only main adds the final words.

Known errors

2. errors.Is finds a known error in the chain

Some errors are values you can compare with, called sentinel errors. os.ErrNotExist is the one for a missing file. errors.Is(err, target) looks through the whole chain for it.

main.go
package main

import (
	"errors"
	"fmt"
	"os"
)

func loadConfig(path string) ([]byte, error) {
	data, err := os.ReadFile(path)
	if err != nil {
		return nil, fmt.Errorf("loading config: %w", err)
	}
	return data, nil
}

func main() {
	_, err := loadConfig("config/channels.json")

	switch {
	case errors.Is(err, os.ErrNotExist):
		fmt.Println("no config file yet; using the defaults")
	case err != nil:
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	default:
		fmt.Println("config loaded")
	}
}
$ go run .
no config file yet; using the defaults

os.ReadFile reads a whole small file into a []byte. Its error is wrapped by loadConfig, yet errors.Is still finds os.ErrNotExist inside. A missing file is an expected case here, so it is handled; any other failure (no permission, a disk error) is still fatal.

Never compare messages: strings.Contains(err.Error(), "no such file") breaks when the wording changes or the program runs on Windows. errors.Is compares the values.

3. Your own sentinel errors

Declare one with errors.New at the top of the file, name it Err…, and wrap it where it happens.

main.go
package main

import (
	"errors"
	"fmt"
)

var ErrFullyBooked = errors.New("fully booked")

func reserve(property string, freeRooms int) error {
	if freeRooms == 0 {
		return fmt.Errorf("reserving %s: %w", property, ErrFullyBooked)
	}
	return nil
}

func main() {
	err := reserve("nyhavn", 0)

	if errors.Is(err, ErrFullyBooked) {
		fmt.Println("offer the waiting list:", err)
		return
	}
	if err != nil {
		fmt.Println("unexpected:", err)
	}
}
$ go run .
offer the waiting list: reserving nyhavn: fully booked

The caller reacts to “fully booked” differently from every other failure, without knowing where in the chain it happened or what words were added around it. It is the Go version of catching a specific exception class.

4. %v instead of %w breaks the chain

%v puts the old error’s text in the message, but not the error itself. The message looks the same; errors.Is no longer finds anything:

main.go
package main

import (
	"errors"
	"fmt"
)

var ErrFullyBooked = errors.New("fully booked")

func main() {
	wrapped := fmt.Errorf("reserving nyhavn: %w", ErrFullyBooked)
	flattened := fmt.Errorf("reserving nyhavn: %v", ErrFullyBooked)

	fmt.Println(wrapped, "|", errors.Is(wrapped, ErrFullyBooked))
	fmt.Println(flattened, "|", errors.Is(flattened, ErrFullyBooked))
}
$ go run .
reserving nyhavn: fully booked | true
reserving nyhavn: fully booked | false

Use %w whenever you pass an error up. Use %v only on purpose, when a caller must not depend on what is inside, for example to hide a database driver’s error behind your package’s own words.

logstat v1 used %v in run, because wrapping had not been taught yet. The build day changes it.

Errors with data

5. An error type, and errors.As

error is an interface with one method, Error() string (the interfaces lesson). Any type with that method is an error, so an error can carry fields. errors.As finds an error of that type in the chain and gives it to you.

main.go
package main

import (
	"errors"
	"fmt"
)

type ValidationError struct {
	Field   string
	Problem string
}

func (e *ValidationError) Error() string {
	return e.Field + ": " + e.Problem
}

func validateGuests(guests int) error {
	if guests < 1 {
		return &ValidationError{Field: "guests", Problem: "must be at least 1"}
	}
	return nil
}

func storeBooking(guests int) error {
	if err := validateGuests(guests); err != nil {
		return fmt.Errorf("storing booking: %w", err)
	}
	return nil
}

func main() {
	err := storeBooking(0)

	var invalid *ValidationError
	if errors.As(err, &invalid) {
		fmt.Printf("422: field %q %s\n", invalid.Field, invalid.Problem)
		return
	}
	if err != nil {
		fmt.Println("500:", err)
	}
}
$ go run .
422: field "guests" must be at least 1

errors.As takes a pointer to a variable of the type you look for, and fills it when it finds one. Here the caller turns a validation failure into a 422 with the field name, and anything else into a 500, which is exactly what an HTTP handler does in Week 5.

The error type uses a pointer receiver and is returned as &ValidationError{…}, the usual style for error structs. errors.Is is for “is it this value?”, errors.As for “is it this type, and what does it say?”.

6. The typed nil trap

An interface holds a type and a value (the interfaces lesson). An error holding a nil *ValidationError has a type, so it is not nil:

main.go
package main

import "fmt"

type ValidationError struct {
	Field   string
	Problem string
}

func (e *ValidationError) Error() string {
	return e.Field + ": " + e.Problem
}

func validate(guests int) *ValidationError {
	if guests < 1 {
		return &ValidationError{Field: "guests", Problem: "must be at least 1"}
	}
	return nil
}

func check(guests int) error {
	return validate(guests)
}

func main() {
	err := check(2)

	fmt.Println(err == nil)
	fmt.Printf("%T\n", err)
}
staticcheck ./...
main.go:28:14: this comparison is never true (SA4023)
	main.go:26:9: the lhs of the comparison is the 1st return value of this function call
	main.go:21:6: hello.check never returns a nil interface value
$ go run .
false
*main.ValidationError

2 guests is valid, and validate returned nil. But check returned that nil pointer as an error, so the error carries the type *ValidationError and err == nil is false. Every caller now thinks the check failed.

staticcheck sees it before the program runs: check can never return a nil interface, so err == nil can never be true. That check is one more reason to run it on every commit.

The rule that prevents it: a function returns error, never a concrete error type. Write validate to return error, and return a plain nil on success. Then this cannot happen.

Coming from PHP

BookingService.php
<?php
try {
    $this->storeBooking($guests);
} catch (ValidationException $e) {           // errors.As
    return response()->json(['errors' => $e->errors()], 422);
} catch (FullyBookedException $e) {          // errors.Is with a sentinel
    return $this->waitingList($e);
}

throw new RuntimeException("storing booking", previous: $e);   // %w

PHP has the same three ideas: an exception class per kind of failure, catch by class, and previous: to chain. The difference is direction. A PHP exception jumps up to whoever catches it; a Go error is returned one level at a time, and each level decides whether to handle it, wrap it or pass it on.

Laravel’s Handler maps exception classes to responses in one place. Go code does the same with one function that uses errors.As and errors.Is, as Week 5 shows.

PracticeA Tour of Go: errors, one small program

In A Tour of Go, do Errors and Exercise: Errors. The exercise’s ErrNegativeSqrt is a non-struct error type, a good contrast with ValidationError.

Exercise: an import report

Write importRow(row []string) error for rows of id,guests. It returns a wrapped ErrBadRow (a sentinel) when the row does not have exactly two fields, and a wrapped *ValidationError when guests is not a number from 1 to 6. In main, import four rows and print, for each failure, either bad row, or the field and problem of the validation error, or the whole message for anything else.

Show the solution
main.go
package main

import (
	"errors"
	"fmt"
	"strconv"
)

var ErrBadRow = errors.New("bad row")

type ValidationError struct {
	Field   string
	Problem string
}

func (e *ValidationError) Error() string {
	return e.Field + ": " + e.Problem
}

func importRow(row []string) error {
	if len(row) != 2 {
		return fmt.Errorf("row with %d fields: %w", len(row), ErrBadRow)
	}
	guests, err := strconv.Atoi(row[1])
	if err != nil || guests < 1 || guests > 6 {
		return fmt.Errorf("booking %s: %w", row[0], &ValidationError{Field: "guests", Problem: "must be a number from 1 to 6"})
	}
	return nil
}

func main() {
	rows := [][]string{{"1042", "2"}, {"1043"}, {"1044", "nine"}, {"1045", "4"}}

	for _, row := range rows {
		err := importRow(row)
		var invalid *ValidationError
		switch {
		case err == nil:
			fmt.Println("imported", row[0])
		case errors.Is(err, ErrBadRow):
			fmt.Println("bad row:", err)
		case errors.As(err, &invalid):
			fmt.Printf("invalid %s: %s\n", invalid.Field, invalid.Problem)
		default:
			fmt.Println("failed:", err)
		}
	}
}
$ go run .
imported 1042
bad row: row with 1 fields: bad row
invalid guests: must be a number from 1 to 6
imported 1045

[][]string is a slice of slices of strings: one row per element. The strconv error is not wrapped here on purpose: the caller gets one clear validation error, and “not a number” and “out of range” are the same problem to a guest.

Remember

  • Pass errors up with %w and a few words about what you were doing; only main adds the final message.
  • errors.Is for a known value, errors.As for a type with data; never compare messages.
  • Return error, never a concrete error type, so nil means nil.

Tomorrow: packages, so that code can be split into folders, and what a capital letter means.