Skip to content

Report Every Problem at Once

The Course
•
24 min study

A validator that stops at the first problem is easy to write and annoying to use. Someone who sends order A3 lamp:0 Tent:1 learns that the lamp quantity is wrong, fixes it, sends it again, and only then hears that Tent is not a valid item name. Reporting every problem in one pass saves that round trip. The ledger's order parser does this: it checks every entry, collects what is wrong, and returns all of it as one error.

errors.Join takes any number of errors and returns a single error that wraps all of them. Its message is the messages of the parts, one per line. errors.Is and errors.As search every part.

Predict and run

validate checks three entries and keeps going after a problem. What is printed, and what do the two errors.Is calls report?

Predict, then run Go
package main

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

var (
	errItem     = errors.New("item names use lowercase letters")
	errQuantity = errors.New("quantity must be 1-1000")
)

func validate(entries []string) error {
	var problems []error
	for _, entry := range entries {
		item, text, _ := strings.Cut(entry, ":")
		if item != strings.ToLower(item) {
			problems = append(problems, fmt.Errorf("%q: %w", item, errItem))
			continue
		}
		if n, err := strconv.Atoi(text); err != nil || n < 1 || n > 1000 {
			problems = append(problems, fmt.Errorf("%q: %w", item, errQuantity))
		}
	}
	return errors.Join(problems...)
}

func main() {
	err := validate([]string{"lamp:0", "Tent:1", "drill:2"})
	fmt.Println(err)
	fmt.Println(errors.Is(err, errItem), errors.Is(err, errQuantity))
	fmt.Println(validate([]string{"drill:2"}))
}
Check your prediction
Text
"lamp": quantity must be 1-1000
"Tent": item names use lowercase letters
true true
<nil>

The last line is <nil>. errors.Join ignores nil arguments, and with nothing left to join it returns nil. That is why validate can always end with return errors.Join(problems...): an empty list means success, with no separate if. Add "hat" to the first list, an entry without a colon, and predict which problem it reports.

One problem per line, or one line per command

A joined error's message contains newlines. That is a sensible default, but the project prints one output line per input command, so it turns the newlines into "; " before printing. The joined error itself is unchanged, so errors.Is still finds every part.

Wrap a joined error and print it on one line Go
package main

import (
	"errors"
	"fmt"
	"strings"
)

var (
	errItem     = errors.New("bad item name")
	errQuantity = errors.New("bad quantity")
)

func main() {
	joined := errors.Join(fmt.Errorf("%q: %w", "lamp", errQuantity), fmt.Errorf("%q: %w", "Tent", errItem))
	err := fmt.Errorf("order A3: %w", joined)
	fmt.Println(strings.ReplaceAll(err.Error(), "\n", "; "))
	fmt.Println(errors.Is(err, errItem))
}
Text
order A3: "lamp": bad quantity; "Tent": bad item name
true

Wrapping with %w adds the order ID in front of the whole group, and the search still reaches both parts. fmt.Errorf also accepts more than one %w in a format. errors.Is searches every wrapped error just as it does with errors.Join, but the message is laid out by the format string, not one error per line. It needs one %w per error, so a slice of problems built in a loop needs errors.Join.

Collect, then decide

The pattern has three steps: collect problems in a slice while checking everything, join them at the end, and return early only for problems that make further checks meaningless. In the project, an order with nine lines is rejected immediately, because checking each line of an oversized order would only produce noise. Bad entries inside an order of a valid size are all collected.

errors.As finds the first match

errors.As on a joined error searches the parts in order and stops at the first one of the right type. If you need every part, the joined error has an Unwrap() []error method. Most callers only need errors.Is, so reach for that method only when you really need each part.

Practice

Exercise

Your turn

Write checkOrder(entries []string) error. Reject an entry that has no : with errFormat, and reject a second entry for the same item with errDuplicate. Wrap a format error with the whole entry in quotes, and a duplicate with the item name in quotes, as the expected output shows. Collect every problem and join them. Check tent:1 tent:2 hat drill:1, then print whether the result matches each sentinel, and check that tent:1 drill:1 returns nil.

The output should be:

Text
"tent": item is listed twice; "hat": use ITEM:QUANTITY
true true
<nil>
Your working space Go
package main

func main() {
	// Write checkOrder, then check both orders.
}
Hint 1: the idea

Track the item names you have already seen in a map[string]bool. A duplicate is a problem, not a reason to stop.

Hint 2: a first step

Use item, _, ok := strings.Cut(entry, ":"). When ok is false, append the format problem and continue to the next entry.

Worked solution
Run the solution Go
package main

import (
	"errors"
	"fmt"
	"strings"
)

var (
	errFormat    = errors.New("use ITEM:QUANTITY")
	errDuplicate = errors.New("item is listed twice")
)

func checkOrder(entries []string) error {
	var problems []error
	seen := make(map[string]bool)
	for _, entry := range entries {
		item, _, ok := strings.Cut(entry, ":")
		if !ok {
			problems = append(problems, fmt.Errorf("%q: %w", entry, errFormat))
			continue
		}
		if seen[item] {
			problems = append(problems, fmt.Errorf("%q: %w", item, errDuplicate))
			continue
		}
		seen[item] = true
	}
	return errors.Join(problems...)
}

func main() {
	err := checkOrder(strings.Fields("tent:1 tent:2 hat drill:1"))
	fmt.Println(strings.ReplaceAll(err.Error(), "\n", "; "))
	fmt.Println(errors.Is(err, errFormat), errors.Is(err, errDuplicate))
	fmt.Println(checkOrder(strings.Fields("tent:1 drill:1")))
}
Text
"tent": item is listed twice; "hat": use ITEM:QUANTITY
true true
<nil>

Both problems were reported from one call, in input order, and drill:1 after them was still checked. The clean order returned nil because errors.Join of an empty list is nil.

Was this article helpful?

Your response is saved on this device.