Errors
Return error values
The error interface is the standard failure signal. nil means success.
import (
"errors"
"fmt"
)
func find(id int) (string, error) {
if id <= 0 {
return "", errors.New("id must be positive")
}
return "ok", nil
}
Check errors immediately
Handle the error before using the result.
name, err := find(0)
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Println(name)
Wrap context
fmt.Errorf with %w wraps an error for later inspection.
return "", fmt.Errorf("find user: %w", err)
Error habits
- Do not ignore errors with a blank identifier casually
- Add context when returning errors up the stack
- Compare sentinel errors with
errors.Is - Panic is for truly unexpected failures, not normal control flow
Comments
One comment per signed-in account. Comments are saved with this page’s URL.