Errors
errors.New, fmt.Errorf with %w, errors.Is, errors.As, and sentinel errors - Go errors are values.
An error is a value that reports a problem. A function often returns it as a second result beside the answer. If the error is nil, the operation succeeded; otherwise, check it before using the answer.
Create a named error value for a problem callers need to recognize. Add an explanatory message with %w when returning it, while keeping the original error available. errors.Is checks whether the error is that named error, even when extra information was added.
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 check its cause with errors.Is or inspect its type with errors.As. This makes the original error available to callers. Add useful context, but do not make callers depend on the wording of an error message.