Error handling: error, errors.Is and errors.As
In many languages errors are exceptions that jump over the code and are caught somewhere else. Go chose another path: errors are ordinary values that functions return, and the caller decides what to do with them. At first it seems repetitive, but it has a big advantage: when reading the code you see exactly where something can fail and how it is handled. In this lesson you will learn the error type, how to create errors, how to wrap them with context and how to inspect them with errors.Is and errors.As.
The error type and the if err != nil pattern
error is a built-in type: an interface with a single method, Error() string. The value nil means no error. By convention, the function returns the error as its last value, and the caller checks it right away. To create simple errors you use errors.New("message"), or fmt.Errorf if you need to format the text. Error messages are written in lowercase and without a final period, because they are often concatenated with other messages. Never ignore an error with the underscore unless you are sure it does not matter.
package main
import (
"errors"
"fmt"
"strconv"
)
func safeDivide(a, b int) (int, error) {
if b == 0 {
return 0, errors.New("division by zero")
}
return a / b, nil
}
func main() {
if res, err := safeDivide(10, 0); err != nil {
fmt.Println("error:", err)
} else {
fmt.Println(res)
}
n, err := strconv.Atoi("12x")
if err != nil {
fmt.Println("cannot convert:", err)
return
}
fmt.Println(n)
}Sentinel errors and wrapping with %w
A sentinel error is a package variable created once, like var ErrNotFound = errors.New("not found"), that others can compare against. As the error goes up through the layers of the program it is convenient to add context: fmt.Errorf with the %w verb wraps the original error inside a new one without losing it. The result is a chain of errors. To query it you do not use ==, which only looks at the outermost error, but errors.Is(err, ErrNotFound), which walks the whole chain looking for a match.
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 "ana", nil
}
func main() {
_, err := findUser(7)
fmt.Println(err) // findUser 7: not found
fmt.Println(err == ErrNotFound) // false
fmt.Println(errors.Is(err, ErrNotFound)) // true
}Custom errors and errors.As
Sometimes an error needs to carry data, for example the field that failed in a validation. For that you define your own type, usually a struct, with an Error() string method: with that it already satisfies the error interface. Later you will see structs and methods in detail; for now just notice the pattern. To recover the concrete type from a chain of errors you use errors.As, which receives a pointer to a variable of that type and fills it if it finds a compatible one. It is Go's equivalent of catching an exception of a specific type.
package main
import (
"errors"
"fmt"
)
type ValidationError struct {
Field string
}
func (e *ValidationError) Error() string {
return "invalid field: " + e.Field
}
func validate(age int) error {
if age < 0 {
return fmt.Errorf("validate: %w", &ValidationError{Field: "age"})
}
return nil
}
func main() {
err := validate(-5)
var vErr *ValidationError
if errors.As(err, &vErr) {
fmt.Println("bad field:", vErr.Field) // bad field: age
}
fmt.Println(err) // validate: invalid field: age
}- Errors are values: they are returned, not thrown.
- Check if err != nil right after the call.
- Add context with fmt.Errorf("...: %w", err).
- Use errors.Is to compare with sentinels and errors.As for types.
- Lowercase messages without a final period.
✎ 我的笔记
仅保存在此浏览器中。登录后可保存到账号。0/5000 字符