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.EntryErrorholds the entry's position and the underlying problem, and returns that problem fromUnwrap. - Sentinels for the kinds of problem. One for a missing colon and one for a quantity outside 1 to 1000.
errors.Join. Collect one*EntryErrorper bad entry and join them. Return nil when nothing is wrong.errors.Isanderrors.Asat the call site.Isanswers "was any quantity wrong?".Asfinds the first entry error and its position.
Plan before you type
- Declare the two sentinels and the
EntryErrortype withPosition intandErr error. - Give
*EntryErroranErrormethod that printsentry 2: ...and anUnwrapmethod. - Write
parseEntries(entries []string) (map[string]int, error). Loop with the index, so you know each position, and collect problems. - Return
niland the joined error when anything is wrong, so a caller cannot use half a result. - 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.Aspanics with*target must be interface or implement error: the target was declared asvar entryErr EntryError. TheErrormethod is on*EntryError, so the target must bevar entryErr *EntryError, the same pointer type the parser stores. (Appending a plainEntryError{...}to a[]errordoesn't even compile, for the same reason.)errors.Is(err, errQuantity)is false although a quantity was bad:EntryErrorhas noUnwrapmethod, so the search cannot get past it.- The map is returned with some entries even though the order is invalid: return
nilfor 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.
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:
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>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
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)
}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.
Completion is saved in this browser only. It does not measure mastery.