Error handling the Go way
Course contents (17 lessons)
- Getting started with Go
- Installing Go 1.25 and your first program
- Variables, types and constants
- Control flow: if, for and switch
- Functions, multiple returns and defer
- Slices and maps
- Arrays and slices
- Maps and working with strings
- Structs, methods and interfaces
- Structs, methods and pointers
- Interfaces
- Errors, packages and generics
- Error handling the Go way
- Packages and modules
- Generics
- Concurrency
- Goroutines and channels
- select, timeouts and context
- Mutexes, sync and the race detector
- Testing
- Testing and benchmarks
- Building and shipping a service
- Building an HTTP JSON API with net/http
- Building and deploying a Go service
Errors are ordinary values
Go has no exceptions. An error is a value that implements a tiny interface:
type error interface {
Error() string
}
Functions that can fail return an error as their last result. The caller checks it. You have seen this already. Now let us look at how to do it well, because the difference between a careless and a careful Go program is mostly in the errors.
Creating, wrapping and checking
package main
import (
"errors"
"fmt"
"os"
)
// Sentinel error: a fixed value callers can compare against.
var ErrOutOfStock = errors.New("out of stock")
// Custom error type: carries extra data.
type ValidationError struct {
Field string
Reason string
}
func (e *ValidationError) Error() string {
return fmt.Sprintf("invalid %s: %s", e.Field, e.Reason)
}
var stock = map[string]int{"tea": 3, "rice": 0}
func reserve(item string, qty int) error {
if qty <= 0 {
return &ValidationError{Field: "qty", Reason: "must be positive"}
}
have, ok := stock[item]
if !ok {
return fmt.Errorf("item %q: %w", item, os.ErrNotExist)
}
if have < qty {
return fmt.Errorf("reserve %d x %s: %w", qty, item, ErrOutOfStock)
}
stock[item] -= qty
return nil
}
func placeOrder(item string, qty int) error {
if err := reserve(item, qty); err != nil {
return fmt.Errorf("place order: %w", err) // add context, keep the cause
}
return nil
}
func main() {
tests := []struct {
item string
qty int
}{{"tea", 2}, {"rice", 1}, {"salt", 1}, {"tea", 0}}
for _, t := range tests {
err := placeOrder(t.item, t.qty)
var ve *ValidationError
switch {
case err == nil:
fmt.Println("ok:", t.item)
case errors.Is(err, ErrOutOfStock):
fmt.Println("sold out ->", err)
case errors.Is(err, os.ErrNotExist):
fmt.Println("unknown item ->", err)
case errors.As(err, &ve):
fmt.Println("bad input on field", ve.Field, "->", err)
default:
fmt.Println("unexpected:", err)
}
}
}
Output:
ok: tea
sold out -> place order: reserve 1 x rice: out of stock
unknown item -> place order: item "salt": file does not exist
bad input on field qty -> place order: invalid qty: must be positive
What this shows
Adding context. fmt.Errorf("place order: %w", err) creates a new error whose message includes the original one. Each layer adds a short phrase about what it was doing, so the final message reads like a trace: place order: reserve 1 x rice: out of stock. Without context, you would just see "out of stock" and have no idea where it came from. Write the context as what you were doing, without repeating the word "error" or "failed" at every level.
The %w verb wraps the original error so it can be found later. Using %v instead of %w gives the same text but loses the link, so errors.Is can no longer find the cause. Mixing these up is the most common wrapping mistake.
errors.Is walks the chain of wrapped errors and asks "is any of these equal to this target?". Use it instead of ==, which would fail as soon as someone wraps the error. errors.As walks the chain looking for an error of a given type and, if found, puts it in your variable so you can read its fields. Note that you pass a pointer to the variable: &ve.
Sentinel values or custom types?
Use a sentinel (var ErrOutOfStock = errors.New(...)) when callers only need to know what happened, such as "not found" or "out of stock". Use a custom type when callers need details, like which field failed. Whichever you choose, it becomes part of your package's public API, so do not export them without a reason.
Combining errors
Since Go 1.20, errors.Join(err1, err2) combines several errors into one, and errors.Is works on the result. It is handy for validating a form and reporting every problem at once:
var errs []error
if name == "" {
errs = append(errs, errors.New("name is required"))
}
if price < 0 {
errs = append(errs, errors.New("price cannot be negative"))
}
if err := errors.Join(errs...); err != nil {
return err
}
errors.Join returns nil when the list is empty, so this works without a length check.
Handle an error once
An error should be either handled or returned, not both. If you log an error and then also return it, the caller probably logs it again, and you get the same problem printed three times. A good rule: deep functions wrap and return, and the top level of the program (main or an HTTP handler) decides what to do, whether that is to log, retry or show a message.
panic and recover
Go also has panic, which stops normal execution and unwinds the stack. It is for programmer errors that should never happen, like an impossible state, or failing to start up because essential configuration is missing. Do not use panic for ordinary failures such as bad user input or a missing file. Libraries should return errors, not panic.
recover catches a panic, but only inside a deferred function. The main legitimate use is at the boundary of a server, so one bad request does not take down the whole process. The standard net/http package already does this for you in each handler.
Common mistakes
- Ignoring errors with _. If a call returns an error and you throw it away, failures will pass silently.
- Comparing error text.
err.Error() == "out of stock"breaks when messages change. Useerrors.Isorerrors.As. - Returning a nil pointer of a custom type as
error. See the interface lesson. - Capitalised, punctuated messages. Convention is lowercase and no trailing full stop, since messages get chained.
Try it yourself
Write a function loadConfig(path string) (Config, error) that opens a file, decodes it with encoding/json and validates a field. Wrap each failure with context. In main, use errors.Is(err, os.ErrNotExist) to print a friendly "config file not found" message, and use a custom validation error type to report which field is wrong.
package main
import (
"errors"
"fmt"
"os"
)
// Sentinel error: a fixed value callers can compare against.
var ErrOutOfStock = errors.New("out of stock")
// Custom error type: carries extra data.
type ValidationError struct {
Field string
Reason string
}
func (e *ValidationError) Error() string {
return fmt.Sprintf("invalid %s: %s", e.Field, e.Reason)
}
var stock = map[string]int{"tea": 3, "rice": 0}
func reserve(item string, qty int) error {
if qty <= 0 {
return &ValidationError{Field: "qty", Reason: "must be positive"}
}
have, ok := stock[item]
if !ok {
return fmt.Errorf("item %q: %w", item, os.ErrNotExist)
}
if have < qty {
return fmt.Errorf("reserve %d x %s: %w", qty, item, ErrOutOfStock)
}
stock[item] -= qty
return nil
}
func placeOrder(item string, qty int) error {
if err := reserve(item, qty); err != nil {
return fmt.Errorf("place order: %w", err) // add context, keep the cause
}
return nil
}
func main() {
tests := []struct {
item string
qty int
}{{"tea", 2}, {"rice", 1}, {"salt", 1}, {"tea", 0}}
for _, t := range tests {
err := placeOrder(t.item, t.qty)
var ve *ValidationError
switch {
case err == nil:
fmt.Println("ok:", t.item)
case errors.Is(err, ErrOutOfStock):
fmt.Println("sold out ->", err)
case errors.Is(err, os.ErrNotExist):
fmt.Println("unknown item ->", err)
case errors.As(err, &ve):
fmt.Println("bad input on field", ve.Field, "->", err)
default:
fmt.Println("unexpected:", err)
}
}
}
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account