Lesson 11 of 20 · Part 3: Functions
Error handling
Go error handling for beginners. Return and check errors, create them with errors.New and fmt.Errorf, wrap with %w, use errors.Is and errors.As, and panic and recover.
5 min read · Updated · Beginner friendly
What you'll learn
- Return errors from functions and check them with if err != nil
- Add context to errors by wrapping them with %w
- Recognise specific errors with errors.Is and errors.As
- Know when (rarely) to use panic and recover
Things go wrong: a file is missing, a user types letters where a number belongs, a server doesn’t answer. Many languages handle this with exceptions that jump out of the code. Go takes a different, simpler approach: an error is just a value that a function returns. You check it like any other value.
The error type
error is a built-in type. A function that can fail returns an error as its last result. If everything went fine, the error is nil:
package main
import (
"fmt"
"strconv"
)
func main() {
for _, input := range []string{"42", "forty-two"} {
n, err := strconv.Atoi(input)
if err != nil {
fmt.Println("could not convert:", err)
continue
}
fmt.Println("converted:", n)
}
}converted: 42
could not convert: strconv.Atoi: parsing "forty-two": invalid syntaxThe pattern if err != nil { ... } is the most common line in all of Go. It makes the failure path visible right where it can happen. You can’t miss it the way you can miss an exception thrown three functions deeper.
Returning your own errors
Use errors.New for a fixed message, or fmt.Errorf to build a message with values in it:
package main
import (
"errors"
"fmt"
)
func withdraw(balance, amount float64) (float64, error) {
if amount <= 0 {
return balance, errors.New("amount must be positive")
}
if amount > balance {
return balance, fmt.Errorf("insufficient funds: balance %.2f, requested %.2f", balance, amount)
}
return balance - amount, nil
}
func main() {
balance := 100.0
for _, amount := range []float64{30, -5, 500} {
newBalance, err := withdraw(balance, amount)
if err != nil {
fmt.Println("error:", err)
continue
}
balance = newBalance
fmt.Println("ok, balance is now", balance)
}
}ok, balance is now 70
error: amount must be positive
error: insufficient funds: balance 70.00, requested 500.00Conventions to follow:
erroris the last return value.- When returning an error, return zero values (or the unchanged input) for the other results.
- Error messages start with a lowercase letter and don’t end with punctuation, because they are often joined into longer messages.
Wrapping errors with context
Low-level errors are often too vague on their own. “file not found”, but which file, and while doing what? Wrap the error with fmt.Errorf and the special verb %w to add context while keeping the original error inside:
package main
import (
"fmt"
"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 main() {
_, err := loadConfig("missing.json")
if err != nil {
fmt.Println(err)
}
}load config: open missing.json: no such file or directoryThe message reads like a trail: what the program was doing, then what went wrong. (On Windows the last part reads “The system cannot find the file specified.”)
Checking for a specific error: errors.Is
Sometimes you need to react to a particular error. Packages often export sentinel errors: named error values you can compare against. Use errors.Is, which also looks inside wrapped errors:
package main
import (
"errors"
"fmt"
"io/fs"
"os"
)
var ErrNotFound = errors.New("not found")
func findUser(id int) (string, error) {
users := map[int]string{1: "Ada", 2: "Grace"}
name, ok := users[id]
if !ok {
return "", fmt.Errorf("find user %d: %w", id, ErrNotFound)
}
return name, nil
}
func main() {
_, err := findUser(7)
if errors.Is(err, ErrNotFound) {
fmt.Println("show a 404 page:", err)
}
_, err = os.Open("nope.txt")
if errors.Is(err, fs.ErrNotExist) {
fmt.Println("the file does not exist")
}
}show a 404 page: find user 7: not found
the file does not existComparing with err == ErrNotFound would fail here, because the error has been wrapped. Always use errors.Is.
Custom error types: errors.As
When an error needs to carry extra data, such as which field was invalid, you can define your own error type. Any type with an Error() string method is an error. (Methods are covered in lesson 12; for now, read func (e *ValidationError) Error() string as “a ValidationError knows how to describe itself”.)
package main
import (
"errors"
"fmt"
)
type ValidationError struct {
Field string
Problem string
}
func (e *ValidationError) Error() string {
return e.Field + ": " + e.Problem
}
func validateAge(age int) error {
if age < 0 || age > 150 {
return &ValidationError{Field: "age", Problem: "must be between 0 and 150"}
}
return nil
}
func main() {
err := fmt.Errorf("register user: %w", validateAge(200))
var vErr *ValidationError
if errors.As(err, &vErr) {
fmt.Println("highlight the form field:", vErr.Field)
}
fmt.Println(err)
}highlight the form field: age
register user: age: must be between 0 and 150errors.As searches the chain of wrapped errors for one of the given type and, if found, stores it in vErr so you can read its fields.
| You want to… | Use |
|---|---|
| create a simple error | errors.New("message") |
| create an error with values | fmt.Errorf("... %d", x) |
| add context and keep the original | fmt.Errorf("doing X: %w", err) |
| check for a specific error value | errors.Is(err, ErrSomething) |
| get a specific error type and its data | errors.As(err, &target) |
Handle each error once
When you get an error, do one of these things:
- Handle it: retry, use a default, or show a message to the user.
- Return it, usually wrapped with context, and let the caller decide.
Avoid logging an error and returning it; the same problem then shows up several times in your logs.
panic and recover
panic stops the normal flow of the program. It is for situations that should never happen if the code is correct, such as an impossible state or a programming mistake. Go itself panics on things like indexing past the end of a slice or dereferencing a nil pointer.
Deferred functions still run during a panic, and a deferred call to recover can stop the panic and turn it back into a normal value:
package main
import "fmt"
func safeDivide(a, b int) (result int, err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("recovered: %v", r)
}
}()
return a / b, nil // integer division by zero panics
}
func main() {
fmt.Println(safeDivide(10, 2))
fmt.Println(safeDivide(1, 0))
fmt.Println("the program keeps running")
}5 <nil>
0 recovered: runtime error: integer divide by zero
the program keeps runningErrors, not panics
Don’t use panic for ordinary failures such as bad input or a missing file. Return an error. Reserve panic for bugs, and recover for special places like the top of a web server’s request handler, where one bad request must not crash the whole server.
Common mistakes
Ignoring errors. n, _ := strconv.Atoi(s) silently turns bad input into 0. Only discard an error when you’re certain it can’t matter.
Using the result when there was an error. If err != nil, the other return values are usually meaningless. Return or continue straight away.
Comparing wrapped errors with ==. Use errors.Is.
Using %v instead of %w when wrapping. %v copies only the text, so errors.Is and errors.As can no longer find the original error.
Exercises
1. Parse a percentage. Write parsePercent(s string) (int, error) that converts a string to an int and returns an error if it isn’t a number or isn’t between 0 and 100. Try it with "75", "150" and "abc".
Show solution
package main
import (
"fmt"
"strconv"
)
func parsePercent(s string) (int, error) {
n, err := strconv.Atoi(s)
if err != nil {
return 0, fmt.Errorf("parse percent %q: %w", s, err)
}
if n < 0 || n > 100 {
return 0, fmt.Errorf("parse percent %q: out of range", s)
}
return n, nil
}
func main() {
for _, s := range []string{"75", "150", "abc"} {
n, err := parsePercent(s)
if err != nil {
fmt.Println("error:", err)
continue
}
fmt.Println("ok:", n)
}
}ok: 75
error: parse percent "150": out of range
error: parse percent "abc": strconv.Atoi: parsing "abc": invalid syntax2. Sentinel error. Create var ErrEmptyCart = errors.New("cart is empty"). Write checkout(items []string) error that returns it wrapped with context when the cart is empty. In main, use errors.Is to print a friendly message.
Show solution
package main
import (
"errors"
"fmt"
)
var ErrEmptyCart = errors.New("cart is empty")
func checkout(items []string) error {
if len(items) == 0 {
return fmt.Errorf("checkout: %w", ErrEmptyCart)
}
fmt.Println("ordering", len(items), "item(s)")
return nil
}
func main() {
if err := checkout(nil); errors.Is(err, ErrEmptyCart) {
fmt.Println("Your cart is empty. Add something first!")
}
if err := checkout([]string{"book"}); err != nil {
fmt.Println("unexpected:", err)
}
}Your cart is empty. Add something first!
ordering 1 item(s)Recap
- Errors are values: functions return an
errorlast, andnilmeans success. - Check with
if err != nilright after the call. - Create errors with
errors.Neworfmt.Errorf; wrap with%wto add context. - Use
errors.Isfor specific error values anderrors.Asfor specific error types. panicis for bugs, not normal failures;recoverin a deferred function can stop a panic.
That completes Part 3. In Part 4 you’ll attach behaviour to your types with methods.
Finished this lesson?
Your progress is saved in this browser only.