Skip to content

Checkpoint: Explain a Rejected Order

The Course
•
30 min study

This checkpoint puts today's two error lessons, error types and joined errors, into one function. An order is a list of ITEM:QUANTITY entries. Your parser must report every bad entry at once, and each report must carry the entry's position as a field, so a caller can point at the exact problem without reading the message. That is the kind of error the ledger's users see when an order is rejected.

What you will use

  • An error type with Unwrap. EntryError holds the entry's position and the underlying problem, and returns that problem from Unwrap.
  • Sentinels for the kinds of problem. One for a missing colon and one for a quantity outside 1 to 1000.
  • errors.Join. Collect one *EntryError per bad entry and join them. Return nil when nothing is wrong.
  • errors.Is and errors.As at the call site. Is answers "was any quantity wrong?". As finds the first entry error and its position.

Plan before you type

  1. Declare the two sentinels and the EntryError type with Position int and Err error.
  2. Give *EntryError an Error method that prints entry 2: ... and an Unwrap method.
  3. Write parseEntries(entries []string) (map[string]int, error). Loop with the index, so you know each position, and collect problems.
  4. Return nil and the joined error when anything is wrong, so a caller cannot use half a result.
  5. In main, print the error on one line, check both sentinels and print the first bad position.
Prove the parser keeps going

Put a bad entry first and another one last. If the output mentions only the first, the loop returns too early. If it mentions both but errors.Is reports false, a %w was written as %v somewhere.

Mistakes worth checking for

  • errors.As panics with *target must be interface or implement error: the target was declared as var entryErr EntryError. The Error method is on *EntryError, so the target must be var entryErr *EntryError, the same pointer type the parser stores. (Appending a plain EntryError{...} to a []error doesn't even compile, for the same reason.)
  • errors.Is(err, errQuantity) is false although a quantity was bad: EntryError has no Unwrap method, so the search cannot get past it.
  • The map is returned with some entries even though the order is invalid: return nil for the result whenever the error is not nil.
  • Positions start at 0 in the message: people count entries from 1, so add 1 to the index.
Exercise

Your turn

Write parseEntries as described. Check tent:2 lamp drill:0 hat:3 and print the joined error on one line, whether it matches each sentinel, and the position of the first bad entry. Then check tent:2 drill:1 and print the parsed quantities.

The output should be:

Text
entry 2: use ITEM:QUANTITY; entry 3: quantity must be 1-1000
true true
First problem at entry 2
map[drill:1 tent:2] <nil>
Your working space Go
package main

func main() {
	// Define the sentinels, EntryError and parseEntries, then check both orders.
}
Hint 1: the idea

Each problem is wrapped twice: the sentinel inside an *EntryError, and all the entry errors inside one joined error.

Hint 2: a first step

Range with for i, entry := range entries and record &EntryError{Position: i + 1, Err: errFormat} when strings.Cut finds no colon.

Worked solution
Run the solution Go
package main

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

var (
	errFormat   = errors.New("use ITEM:QUANTITY")
	errQuantity = errors.New("quantity must be 1-1000")
)

type EntryError struct {
	Position int
	Err      error
}

func (e *EntryError) Error() string {
	return fmt.Sprintf("entry %d: %v", e.Position, e.Err)
}

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

func parseEntries(entries []string) (map[string]int, error) {
	quantities := make(map[string]int)
	var problems []error
	for i, entry := range entries {
		item, text, ok := strings.Cut(entry, ":")
		if !ok {
			problems = append(problems, &EntryError{Position: i + 1, Err: errFormat})
			continue
		}
		n, err := strconv.Atoi(text)
		if err != nil || n < 1 || n > 1000 {
			problems = append(problems, &EntryError{Position: i + 1, Err: errQuantity})
			continue
		}
		quantities[item] = n
	}
	if err := errors.Join(problems...); err != nil {
		return nil, err
	}
	return quantities, nil
}

func main() {
	_, err := parseEntries(strings.Fields("tent:2 lamp drill:0 hat:3"))
	fmt.Println(strings.ReplaceAll(err.Error(), "\n", "; "))
	fmt.Println(errors.Is(err, errFormat), errors.Is(err, errQuantity))
	var entryErr *EntryError
	if errors.As(err, &entryErr) {
		fmt.Println("First problem at entry", entryErr.Position)
	}
	quantities, err := parseEntries(strings.Fields("tent:2 drill:1"))
	fmt.Println(quantities, err)
}
Text
entry 2: use ITEM:QUANTITY; entry 3: quantity must be 1-1000
true true
First problem at entry 2
map[drill:1 tent:2] <nil>

hat:3 came after two bad entries and was still parsed, but it does not appear anywhere, because an invalid order returns no quantities at all. errors.As stopped at entry 2, the first entry error in the joined list, while errors.Is searched them all.

Was this article helpful?

Your response is saved on this device.