Skip to content

Carry Details in an Error Type

The Course
•
32 min study

In the intermediate course every rejection was a sentinel: a fixed value such as errDuplicate, matched with errors.Is. A sentinel answers one question, "which kind of failure was this?". Sometimes the caller needs more. When an order is short of stock, the caller may want to know which item was short and by how much, to offer a smaller order or to restock. Packing that into the message text and parsing it back out would be fragile. Instead, define a type that implements the error interface and carries the details as fields.

Any type with an Error() string method is an error. A struct pointer is the usual choice, so the method is declared on *ShortageError, and the code that fails returns &ShortageError{...}.

Predict and run

reserve wraps the shortage with the order ID. errors.As searches the chain for a *ShortageError. What does main print?

Predict, then run Go
package main

import (
	"errors"
	"fmt"
)

type ShortageError struct {
	Item string
	Have int
	Need int
}

func (e *ShortageError) Error() string {
	return fmt.Sprintf("not enough %s: have %d, need %d", e.Item, e.Have, e.Need)
}

func reserve(id, item string, have, need int) error {
	if need > have {
		return fmt.Errorf("order %s: %w", id, &ShortageError{Item: item, Have: have, Need: need})
	}
	return nil
}

func main() {
	err := reserve("A2", "tent", 3, 4)
	fmt.Println(err)
	var shortage *ShortageError
	if errors.As(err, &shortage) {
		fmt.Println("Short by", shortage.Need-shortage.Have, shortage.Item)
	}
}
Check your prediction
Text
order A2: not enough tent: have 3, need 4
Short by 1 tent

The error message still reads naturally, because fmt.Errorf calls Error() on the wrapped value. The caller, though, did not parse any text: it read Need and Have as numbers. Change need to 3 and run again. reserve returns nil, errors.As reports false, and only <nil> is printed.

How errors.As matches

errors.As(err, &target) walks the chain of wrapped errors from the outside in. At each step it asks whether the error can be assigned to the type of target. On the first match it stores the error in target and returns true. Three details matter:

  • Pass a pointer to your variable. target has type *ShortageError, so you pass &shortage, a **ShortageError. Passing shortage itself is a mistake that go vet reports.
  • Match the type you return. The code returns &ShortageError{...}, so the chain contains a *ShortageError. A target of type ShortageError, without the star, would never match.
  • Nil is not a match. errors.As(nil, &shortage) is false, so the if doubles as an error check.

Wrap with your own type

A type of your own can also wrap another error. Give it an Unwrap() error method that returns the inner error, and errors.Is and errors.As will look through it. LineError below adds a line number to any error, and errors.Is still finds the sentinel inside.

A wrapper type with Unwrap Go
package main

import (
	"errors"
	"fmt"
)

var errQuantity = errors.New("quantity must be 1-1000")

type LineError struct {
	Line int
	Err  error
}

func (e *LineError) Error() string {
	return fmt.Sprintf("line %d: %v", e.Line, e.Err)
}

func (e *LineError) Unwrap() error {
	return e.Err
}

func main() {
	err := fmt.Errorf("read input: %w", &LineError{Line: 4, Err: errQuantity})
	fmt.Println(err)
	fmt.Println(errors.Is(err, errQuantity))
	var lineErr *LineError
	if errors.As(err, &lineErr) {
		fmt.Println("Fix line", lineErr.Line)
	}
}
Text
read input: line 4: quantity must be 1-1000
true
Fix line 4

The chain here has three links: the fmt.Errorf wrapper, the *LineError, and the sentinel. errors.Is reaches the sentinel through Unwrap. errors.As stops one step earlier, at the *LineError.

The nil pointer that isn't a nil error

Pointer error types come with one classic trap. Here a helper returns the concrete type *ShortageError, and nil when there is enough stock. reserve passes its result on as an error. Two tents are wanted and five are in stock. Predict whether the order is accepted.

Predict, then run Go
package main

import (
	"fmt"
)

type ShortageError struct {
	Item string
	Have int
}

func (e *ShortageError) Error() string {
	return fmt.Sprintf("%s: only %d left", e.Item, e.Have)
}

func check(item string, have, want int) *ShortageError {
	if want > have {
		return &ShortageError{Item: item, Have: have}
	}
	return nil
}

func reserve(item string, have, want int) error {
	return check(item, have, want)
}

func main() {
	err := reserve("tent", 5, 2)
	if err != nil {
		fmt.Println("order failed:", err)
		return
	}
	fmt.Println("order accepted")
}
Check your prediction
Text
order failed: <nil>

The order fails with an error that prints as <nil>. Recall that an interface value is a pair: a type and a value. check returned a nil *ShortageError. When reserve converted it to error, the interface got the type *ShortageError and the value nil. An interface is equal to nil only when both halves are empty, and this one has a type, so err != nil is true. fmt then tries to call Error on the nil pointer, notices the nil receiver and prints <nil>, which makes the bug even more confusing. go vet does not catch it.

The rule that avoids it: a function that can fail returns the error interface type, never a concrete error type, and returns a literal nil on success. Build the concrete value only on the failure path:

Return error, not *ShortageError Go
package main

import (
	"fmt"
)

type ShortageError struct {
	Item string
	Have int
}

func (e *ShortageError) Error() string {
	return fmt.Sprintf("%s: only %d left", e.Item, e.Have)
}

func check(item string, have, want int) error {
	if want > have {
		return &ShortageError{Item: item, Have: have}
	}
	return nil
}

func reserve(item string, have, want int) error {
	return check(item, have, want)
}

func main() {
	for _, want := range []int{2, 9} {
		if err := reserve("tent", 5, want); err != nil {
			fmt.Println("order failed:", err)
			continue
		}
		fmt.Println("order accepted")
	}
}
Text
order accepted
order failed: tent: only 5 left

The only change is check's result type. Now its return nil is a nil error, with no type inside, and callers that want the details still get them with errors.As. Watch for the same trap with a variable: var e *ShortageError followed later by return e returns a non-nil error even when e was never set.

Sentinel or type?

Use a sentinel when the caller only needs to know which failure happened. Use an error type when the caller needs data from the failure. The project uses both: sentinels such as errConflict for simple rejections, and *ShortageError because the shortage has numbers worth reading.

Practice

Exercise

Your turn

Define CapacityError with fields Item and Limit, and an Error method that prints tent cannot hold more than 10000. Write addStock(item string, have, n int) (int, error), which returns a *CapacityError when have + n would pass 10000. Wrap it with fmt.Errorf("stock: %w", ...) at the call site, then use errors.As to print the limit. Check 9990 plus 10, which must succeed, and 9990 plus 11.

The output should be:

Text
10000 <nil>
stock: tent cannot hold more than 10000
Limit: 10000
Your working space Go
package main

func main() {
	// Define CapacityError and addStock, then check both cases.
}
Hint 1: the idea

The function that knows the limit creates the error. The caller adds context with %w without losing the type.

Hint 2: a first step

Compare n > 10000-have. It means the same as have+n > 10000, but it cannot overflow when the numbers are large, which you will need on Day 4.

Worked solution
Run the solution Go
package main

import (
	"errors"
	"fmt"
)

type CapacityError struct {
	Item  string
	Limit int
}

func (e *CapacityError) Error() string {
	return fmt.Sprintf("%s cannot hold more than %d", e.Item, e.Limit)
}

func addStock(item string, have, n int) (int, error) {
	const limit = 10000
	if n > limit-have {
		return 0, &CapacityError{Item: item, Limit: limit}
	}
	return have + n, nil
}

func main() {
	total, err := addStock("tent", 9990, 10)
	fmt.Println(total, err)
	_, err = addStock("tent", 9990, 11)
	err = fmt.Errorf("stock: %w", err)
	fmt.Println(err)
	var capacity *CapacityError
	if errors.As(err, &capacity) {
		fmt.Println("Limit:", capacity.Limit)
	}
}
Text
10000 <nil>
stock: tent cannot hold more than 10000
Limit: 10000

9990 plus 10 lands exactly on the limit and is accepted, and one more unit is rejected, so both sides of the boundary are checked. The caller read Limit from the error without parsing the message.

Was this article helpful?

Your response is saved on this device.