Error handling
Go has no exceptions. A function that can fail returns an error value, and the caller decides what to do with it, right there. It's more typing than try/catch, but every place that can fail is visible in the code, and errors can't escape unnoticed through ten layers of calls.
The basic pattern
package main
import (
"fmt"
"os"
"strconv"
)
func main() {
n, err := strconv.Atoi("12x")
if err != nil {
fmt.Println("could not parse:", err)
} else {
fmt.Println("parsed", n)
}
data, err := os.ReadFile("/no/such/config.yaml")
if err != nil {
fmt.Println("could not read config:", err)
return
}
fmt.Println(len(data))
}could not parse: strconv.Atoi: parsing "12x": invalid syntax could not read config: open /no/such/config.yaml: no such file or directory
error is just an interface with one method, Error() string. nil means "no error". The rule: check every error, immediately, and handle it, return it, or (rarely, and deliberately) ignore it with _.
Creating errors
package main
import (
"errors"
"fmt"
)
func withdraw(balance, amount int) (int, error) {
if amount <= 0 {
return balance, errors.New("amount must be positive")
}
if amount > balance {
return balance, fmt.Errorf("insufficient funds: balance %d, requested %d", balance, amount)
}
return balance - amount, nil
}
func main() {
for _, amt := range []int{30, -5, 500} {
b, err := withdraw(100, amt)
if err != nil {
fmt.Println("error:", err)
continue
}
fmt.Println("new balance:", b)
}
}new balance: 70 error: amount must be positive error: insufficient funds: balance 100, requested 500
Error messages are lowercase and don't end with punctuation, because they're often joined together into longer messages, as you'll see next.
Wrapping: adding context
A bare "file not found" deep inside a program isn't helpful. Which file, doing what? Each layer adds context by wrapping the error with %w:
package main
import (
"errors"
"fmt"
"io/fs"
"os"
)
func loadConfig(path string) ([]byte, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("load config: %w", err)
}
return data, nil
}
func startServer() error {
if _, err := loadConfig("/etc/shop/config.yaml"); err != nil {
return fmt.Errorf("start server: %w", err)
}
return nil
}
func main() {
err := startServer()
fmt.Println(err)
// the original error is still inside, and can be checked:
fmt.Println("is 'not exist'?", errors.Is(err, fs.ErrNotExist))
}start server: load config: open /etc/shop/config.yaml: no such file or directory is 'not exist'? true
The message reads like a trail of breadcrumbs from the top of the program to the root cause. %w keeps the original error inside, so callers can still check what it was; %v would only copy its text.
Checking errors: errors.Is and errors.As
Sentinel errors
A sentinel is a specific error value that callers compare against:
package main
import (
"errors"
"fmt"
)
var ErrNotFound = errors.New("not found")
var ErrForbidden = errors.New("forbidden")
func getOrder(id int, user string) (string, error) {
if user != "admin" && id == 1 {
return "", ErrForbidden
}
if id > 100 {
return "", fmt.Errorf("order %d: %w", id, ErrNotFound)
}
return fmt.Sprintf("order %d", id), nil
}
func main() {
for _, id := range []int{5, 500, 1} {
o, err := getOrder(id, "asha")
switch {
case errors.Is(err, ErrNotFound):
fmt.Println("404:", err)
case errors.Is(err, ErrForbidden):
fmt.Println("403:", err)
case err != nil:
fmt.Println("500:", err)
default:
fmt.Println("200:", o)
}
}
}200: order 5 404: order 500: not found 403: forbidden
errors.Is looks through every layer of wrapping, so order 500: not found still matches ErrNotFound. Never compare error strings: messages change, values don't. The standard library has many sentinels, like io.EOF, fs.ErrNotExist and sql.ErrNoRows.
Custom error types
When callers need more than "which error", such as a field name or a status code, define a type:
package main
import (
"errors"
"fmt"
)
type ValidationError struct {
Field string
Reason string
}
func (e *ValidationError) Error() string {
return fmt.Sprintf("invalid %s: %s", e.Field, e.Reason)
}
func register(email string, age int) error {
if age < 13 {
return &ValidationError{Field: "age", Reason: "must be at least 13"}
}
if email == "" {
return &ValidationError{Field: "email", Reason: "is required"}
}
return nil
}
func handle(email string, age int) {
err := register(email, age)
if err == nil {
fmt.Println("registered", email)
return
}
err = fmt.Errorf("signup: %w", err)
var ve *ValidationError
if errors.As(err, &ve) {
fmt.Printf("400 Bad Request, field %q: %s\n", ve.Field, ve.Reason)
} else {
fmt.Println("500:", err)
}
}
func main() {
handle("asha@example.com", 31)
handle("kid@example.com", 9)
handle("", 20)
}registered asha@example.com 400 Bad Request, field "age": must be at least 13 400 Bad Request, field "email": is required
errors.As finds the first error in the chain of that type and fills in ve, so you can read its fields.
Several errors at once: errors.Join
package main
import (
"errors"
"fmt"
)
func validate(name string, port int) error {
var errs []error
if name == "" {
errs = append(errs, errors.New("name is empty"))
}
if port < 1 || port > 65535 {
errs = append(errs, fmt.Errorf("port %d out of range", port))
}
return errors.Join(errs...) // nil if errs is empty
}
func main() {
fmt.Println(validate("api", 8080))
err := validate("", 70000)
fmt.Println(err)
}<nil> name is empty port 70000 out of range
Cleanup with defer, even on errors
Because every error path is an early return, defer is what guarantees cleanup:
package main
import (
"bufio"
"fmt"
"os"
)
func countLines(path string) (n int, err error) {
f, err := os.Open(path)
if err != nil {
return 0, fmt.Errorf("count lines: %w", err)
}
defer f.Close()
sc := bufio.NewScanner(f)
for sc.Scan() {
n++
}
if err := sc.Err(); err != nil {
return n, fmt.Errorf("count lines in %s: %w", path, err)
}
return n, nil
}
func main() {
os.WriteFile("notes.txt", []byte("one\ntwo\nthree\n"), 0o644)
fmt.Println(countLines("notes.txt"))
fmt.Println(countLines("missing.txt"))
}3 <nil> 0 count lines: open missing.txt: no such file or directory
panic is for bugs
Use panic only for situations that mean the program itself is broken (an impossible state, a programming error) or during start-up when the program can't run at all. Everything that can go wrong in normal operation (bad input, network failures, missing files) is an error.
package main
import (
"fmt"
"regexp"
)
// MustCompile panics on a bad pattern: fine for a constant pattern written by the programmer.
var emailRe = regexp.MustCompile(`^[^@\s]+@[^@\s]+\.[a-z]{2,}$`)
func main() {
for _, e := range []string{"asha@example.com", "not-an-email"} {
fmt.Println(e, emailRe.MatchString(e))
}
_, err := regexp.Compile(`([a-z`) // a pattern from user input: handle the error
fmt.Println("error:", err)
}asha@example.com true not-an-email false error: error parsing regexp: missing closing ]: `[a-z`
Functions named MustXxx panic instead of returning an error. They're meant for values fixed in the source code, where a failure is a bug you'll see the first time the program runs.
Handling errors well
| Do | Don't |
|---|---|
Check every err right after the call |
x, _ := f() for errors you can't really ignore |
Add context: fmt.Errorf("save order %d: %w", id, err) |
Wrap with no new information: fmt.Errorf("error: %w", err) |
| Handle an error once: either log it or return it | Log it and return it (it gets logged at every level) |
Use errors.Is / errors.As |
Compare err.Error() strings |
Return nil explicitly on success |
Return a typed nil pointer as an error |
Practice
- Write
func parsePort(s string) (int, error)that returns a clear error for non-numbers and for values outside 1–65535. - Define
var ErrEmptyCart = errors.New("cart is empty"), return it wrapped from acheckoutfunction, and detect it witherrors.Is. - Create a
*HTTPErrortype with aCode intfield and useerrors.Asto read the code from a wrapped error. - Validate a struct with three fields and report all problems at once with
errors.Join.
1.What does %w do in fmt.Errorf("load: %w", err)?
2.How do you check whether a wrapped error is fs.ErrNotExist?
3.When is panic appropriate?
4.What does errors.As(err, &ve) do?