Errors as values
error is an interface with an Error method. You check it immediately, rather than saving it until the end of the function.
error is an interface:
type error interface {
Error() string
}
Any type with that method is an error. Most of the time errors.New or fmt.Errorf is enough. The error text is for a human in a log. Code does not rely on the text: it will be translated, extended, and the comparison will break.
The accepted order of the check is immediately after the call:
user, err := store.Find(id)
if err != nil {
return fmt.Errorf("find user %d: %w", id, err)
}
Do not keep working with a zero user if err != nil. A zero value together with an error means "there is no result". Using user in that branch is a mistake.
A sentinel is a package variable var ErrNotFound = errors.New("not found"). It is compared with errors.Is, not with == against a string and not with err.Error() == "not found". A sentinel is good when the caller needs to tell one expected situation apart: not found, already exists, the context was canceled. For everything else a wrapped error with no new type is enough.
Do not log and return the same error. Someone above will also write it to the log, and the journal will have three copies. Logging happens at the request boundary. Inside a library the error is returned.
A panic is not for "the user sent a crooked id". There is error for that. Panic remains for a broken invariant that means a bug in the program.
Practice
Comparing errors
How does code tell "not found" apart from other errors, if the package author declared
var ErrNotFound = errors.New("not found")?- err.Error() == "not found"
- errors.Is(err, ErrNotFound)
- strings.Contains(err.Error(), "not")
- err == nil || err != nil
Log or return
A library function could not read a file. What should it do with the error?
- Write to the log and return nil, so the caller does not worry
- Return the error and do not log it yourself
- Call panic, so a log is sure to appear
- Write to the log and return the same error
What you must not do with err
After
user, err := find()the conditionerr != nilis true. In that branch, may you read the fields ofuseras real data? Writeyesorno.