Errors
errors.New, fmt.Errorf with %w, errors.Is, errors.As, and sentinel errors - Go errors are values.
An error is a value returned by a function, often as its second result. Callers check it before using the other result.
Create a sentinel error for a condition callers may need to identify. Wrap it with %w to add context, then use errors.Is instead of comparing error text.
package main
import (
"errors"
"fmt"
)
var ErrNotFound = errors.New("not found")
func findUser(id int) (string, error) {
if id != 1 {
return "", fmt.Errorf("findUser %d: %w", id, ErrNotFound)
}
return "Alice", nil
}
func main() {
name, err := findUser(2)
if err != nil {
fmt.Println(err)
if errors.Is(err, ErrNotFound) {
fmt.Println("user does not exist")
}
return
}
fmt.Println(name)
}In production
Wrap an error with %w when callers should be able to inspect its cause with errors.Is or errors.As. Wrapping makes that cause part of the observable API. Add useful context, and do not use message text as a machine-readable contract.
Enjoyed this? Get more software craft delivered to your inbox.