Adding context to an error
In a real program, one function calls another, which calls another. When the deepest call fails, its error message often has no context. Here loadConfig calls readPort, which calls strconv.Atoi:
package main
import (
"fmt"
"strconv"
)
func readPort(text string) (int, error) {
return strconv.Atoi(text)
}
func loadConfig(portText string) error {
_, err := readPort(portText)
return err
}
func main() {
err := loadConfig("80a")
fmt.Println(err)
}
Output:
strconv.Atoi: parsing "80a": invalid syntax
The message says what went wrong, but not where. Was 80a a port, an age or a price? In a big program you could not tell.
Adding context with %w
To fix this, each function can wrap the error: it makes a new error that adds a short note in front and keeps the old error inside. You do this with fmt.Errorf and the special verb %w:
package main
import (
"fmt"
"strconv"
)
func readPort(text string) (int, error) {
port, err := strconv.Atoi(text)
if err != nil {
return 0, fmt.Errorf("read port: %w", err)
}
return port, nil
}
func loadConfig(portText string) error {
_, err := readPort(portText)
if err != nil {
return fmt.Errorf("load config: %w", err)
}
return nil
}
func main() {
err := loadConfig("80a")
fmt.Println(err)
}
Output:
load config: read port: strconv.Atoi: parsing "80a": invalid syntax
Now the message reads from the outside in, like a path to the problem. Each layer adds only a few words about what it was doing. Keep these notes short and in lower case, so the full message stays easy to read.
errors.Is looks inside
A wrapped error is a new value, so == no longer matches a sentinel error. errors.Is does. It looks at the error, then at the error inside it, and so on, until it finds a match:
errEmpty := errors.New("cart is empty")
err := fmt.Errorf("checkout: %w", errEmpty)
fmt.Println(err)
fmt.Println(err == errEmpty)
fmt.Println(errors.Is(err, errEmpty))
Output:
checkout: cart is empty
false
true
This is why Go programmers prefer errors.Is over == for errors. It still works after someone adds context.
%w and %v are different
%v also puts the error's text into the message, so the printed text looks the same. But %v only copies the text. The original error is not kept inside:
err2 := fmt.Errorf("checkout: %v", errEmpty)
fmt.Println(err2)
fmt.Println(errors.Is(err2, errEmpty))
Output:
checkout: cart is empty
false
The message is the same as before, but errors.Is cannot find errEmpty any more. Use %w when you add context to an error, so the caller can still check what caused it.
errors.As looks inside too
errors.As from the last lesson also searches through wrapped errors. strconv has its own error type, *strconv.NumError, a pointer to a struct. Its Num field holds the text that could not be converted. numErr below is already a pointer, but errors.As still needs &numErr, so it can fill numErr in:
_, err := strconv.Atoi("80a")
wrapped := fmt.Errorf("read port: %w", err)
var numErr *strconv.NumError
if errors.As(wrapped, &numErr) {
fmt.Println("bad text:", numErr.Num)
}
Output:
bad text: 80a
In the exercise, wrap the error from validateID with %w, then use errors.Is to check for ErrInvalidID.