A bare sentinel says what went wrong but not where. duplicate ID on its own doesn't tell the person running the queue which line of their input caused it. Adding context, line 4: add task 7: duplicate ID, fixes that, but if adding context destroyed the sentinel, callers could no longer recognise the error. Go's answer is wrapping: a new error that carries extra text and keeps the original inside it.
The %w verb in fmt.Errorf wraps an error. errors.Is looks through every layer of wrapping for the value you ask about. The similar-looking %v only copies the cause's text into the new message, so the chain is cut and errors.Is can no longer find the cause.
Predict and run
Can the caller still recognize the duplicate?
package main
import (
"errors"
"fmt"
)
var errDuplicate = errors.New("duplicate ID")
func main() {
err := fmt.Errorf("add task 7: %w", errDuplicate)
fmt.Println(err)
fmt.Println(errors.Is(err, errDuplicate))
}Check your prediction
add task 7: duplicate ID
trueTrace two layers
Each function adds the context it knows about and passes the error up. add knows the task ID; runLine knows the line number. Follow the error from the bottom up:
package main
import (
"errors"
"fmt"
)
var errDuplicate = errors.New("duplicate ID")
func add(id int) error {
return fmt.Errorf("add task %d: %w", id, errDuplicate)
}
func runLine(n, id int) error {
if err := add(id); err != nil {
return fmt.Errorf("line %d: %w", n, err)
}
return nil
}
func main() {
err := runLine(4, 7)
fmt.Println(err)
fmt.Println(errors.Is(err, errDuplicate))
fmt.Println(errors.Unwrap(err))
}line 4: add task 7: duplicate ID
true
add task 7: duplicate IDThe message reads from the outside in: line, then task, then cause. errors.Unwrap peels off one layer, which shows the error runLine wrapped. errors.Is peels off layers until it finds errDuplicate or runs out. You rarely call Unwrap yourself; it is here to show that the layers are really there.
Find the bug
This program should count how many lines failed with a duplicate ID. The messages look perfect, yet the count is zero. Which verb is wrong?
package main
import (
"errors"
"fmt"
)
var errDuplicate = errors.New("duplicate ID")
func add(seen map[int]bool, id int) error {
if seen[id] {
return fmt.Errorf("add task %d: %v", id, errDuplicate)
}
seen[id] = true
return nil
}
func main() {
seen := map[int]bool{}
duplicates := 0
for _, id := range []int{3, 5, 3, 3} {
if err := add(seen, id); err != nil {
fmt.Println(err)
if errors.Is(err, errDuplicate) {
duplicates++
}
}
}
fmt.Println("Duplicates:", duplicates)
}add task 3: duplicate ID
add task 3: duplicate ID
Duplicates: 0Check your fix
%v formats errDuplicate as text, so the returned error contains the words but not the value. Wrap it with %w:
package main
import (
"errors"
"fmt"
)
var errDuplicate = errors.New("duplicate ID")
func add(seen map[int]bool, id int) error {
if seen[id] {
return fmt.Errorf("add task %d: %w", id, errDuplicate)
}
seen[id] = true
return nil
}
func main() {
seen := map[int]bool{}
duplicates := 0
for _, id := range []int{3, 5, 3, 3} {
if err := add(seen, id); err != nil {
fmt.Println(err)
if errors.Is(err, errDuplicate) {
duplicates++
}
}
}
fmt.Println("Duplicates:", duplicates)
}add task 3: duplicate ID
add task 3: duplicate ID
Duplicates: 2This bug hides well because the printed message is identical either way. Only code that asks errors.Is notices, which is why the Day 7 checks test the error value and not just the text.
Practice
Your turn
The starter has parseMinutes, which returns the sentinel errRange for a number outside 1 to 240. Write readAll(lines []string) (int, error), which adds up the minutes on every line and stops at the first bad one, returning an error that names the line number, counting from 1. Then, in main, print the error and say whether it was a range problem. The output should be:
line 3: 300: minutes out of range
range problem: truepackage main
import (
"errors"
"fmt"
"strconv"
)
var errRange = errors.New("minutes out of range")
func parseMinutes(text string) (int, error) {
n, err := strconv.Atoi(text)
if err != nil {
return 0, err
}
if n < 1 || n > 240 {
return 0, fmt.Errorf("%d: %w", n, errRange)
}
return n, nil
}
func main() {
lines := []string{"30", "45", "300", "20"}
fmt.Println(lines)
}Hint 1: the idea
parseMinutes already wraps the sentinel with the number. readAll knows one more thing, the line number, so it wraps once more, with %w again, and the sentinel is still at the bottom of the chain for main to find.
Hint 2: a first step
Range over lines with the index and, when parseMinutes fails, return its error unchanged at first. Print it in main and check errors.Is already works. Then wrap it with the line number, keeping the cause reachable, and run again.
Worked solution
package main
import (
"errors"
"fmt"
"strconv"
)
var errRange = errors.New("minutes out of range")
func parseMinutes(text string) (int, error) {
n, err := strconv.Atoi(text)
if err != nil {
return 0, err
}
if n < 1 || n > 240 {
return 0, fmt.Errorf("%d: %w", n, errRange)
}
return n, nil
}
func readAll(lines []string) (int, error) {
total := 0
for i, line := range lines {
n, err := parseMinutes(line)
if err != nil {
return 0, fmt.Errorf("line %d: %w", i+1, err)
}
total += n
}
return total, nil
}
func main() {
lines := []string{"30", "45", "300", "20"}
_, err := readAll(lines)
fmt.Println(err)
fmt.Println("range problem:", errors.Is(err, errRange))
}line 3: 300: minutes out of range
range problem: trueTwo layers of %w sit between main and the sentinel, and errors.Is sees through both. Change the input's "300" to "abc" and range problem becomes false, while the message still names line 3: the cause is now strconv's own error, wrapped the same way.
Completion is saved in this browser only. It does not measure mastery.