Errors, panic and recover

Intermediate

Introduction

Things go wrong: a file is missing, a number is typed wrongly, a division has zero below the line. Languages such as Java and Python use exceptions that jump out of the code. Go does it differently and more plainly. A function that can fail returns an error as one of its values, and the caller must look at it. This makes the failure paths visible in the code, which is why Go programs are easy to follow and to trust. This lesson shows how to create, check and wrap errors, and the rare cases where panic and recover are used.

How it works

error is a built-in interface with one method, Error() string. A function that can fail returns an error as its last result. If everything went well, the error is nil. The caller checks it at once:

n, err := strconv.Atoi("12x")
if err != nil {
	fmt.Println("bad number:", err)
	return
}

This if err != nil check is the most common pattern in Go. You create an error with errors.New("text"), or with fmt.Errorf("format", values...) when the message needs values. An error made once at package level, such as var ErrEmpty = errors.New("stack empty"), is a sentinel error: callers can compare against it.

To add context while keeping the original error, wrap it with the verb %w: fmt.Errorf("line %d: %w", n, ErrEmpty). The text now says where the problem happened, and the cause is still inside. Two functions look inside wrapped errors. errors.Is(err, ErrEmpty) is true if ErrEmpty is anywhere in the chain. errors.As(err, &target) finds an error of a certain type and stores it in target, so you can read its fields.

You can define your own error type: any type with an Error() string method is an error. A custom type carries extra data, such as the value that was out of range:

type RangeError struct {
	Value, Max int
}

func (e *RangeError) Error() string {
	return fmt.Sprintf("value %d is above %d", e.Value, e.Max)
}

panic is different. It stops the normal flow of the program and runs the deferred calls on the way out. Go itself panics when you use an index that does not exist or divide an integer by zero. You should call panic yourself only for bugs and situations that must never happen, not for ordinary errors such as bad input. A deferred function can call recover, which stops the panic and returns the panic value. This is useful at the edge of a program, for example in a server that must keep running when one request goes wrong:

defer func() {
	if r := recover(); r != nil {
		err = fmt.Errorf("recovered: %v", r)
	}
}()

Example

package main

import (
	"errors"
	"fmt"
	"strconv"
)

var ErrNegative = errors.New("negative number")

type RangeError struct {
	Value, Max int
}

func (e *RangeError) Error() string {
	return fmt.Sprintf("value %d is above %d", e.Value, e.Max)
}

func check(n int) error {
	if n > 100 {
		return &RangeError{Value: n, Max: 100}
	}
	if n < 0 {
		return fmt.Errorf("check %d: %w", n, ErrNegative)
	}
	return nil
}

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
}

func main() {
	for _, n := range []int{50, -4, 500} {
		err := check(n)
		if err == nil {
			fmt.Println(n, "ok")
			continue
		}
		fmt.Println(err)
		if errors.Is(err, ErrNegative) {
			fmt.Println("  it is negative")
		}
		var re *RangeError
		if errors.As(err, &re) {
			fmt.Println("  the limit is", re.Max)
		}
	}

	_, err := strconv.Atoi("12x")
	fmt.Println(err)

	q, err := safeDivide(10, 2)
	fmt.Println(q, err)
	q, err = safeDivide(1, 0)
	fmt.Println(q, err)
}

Line by line

  1. ErrNegative is a sentinel error made with errors.New; RangeError is a custom error type with its own message.
  2. check returns nil for a good value, a RangeError for a number above 100 and a wrapped ErrNegative for a negative one.
  3. In main, errors.Is detects the sentinel inside the wrapped error, and errors.As pulls out the RangeError so its Max field can be read.
  4. strconv.Atoi("12x") returns an error, which is printed.
  5. safeDivide divides integers; with zero below the line Go panics, and the deferred function recovers and returns an error instead.

Expected result

50 ok
check -4: negative number
  it is negative
value 500 is above 100
  the limit is 100
strconv.Atoi: parsing "12x": invalid syntax
5 <nil>
0 recovered: runtime error: integer divide by zero

In the real world

Almost every Go function that touches the outside world returns an error: reading a file, calling a web service, parsing text. Good programs add context as the error travels up (load config: open file: permission denied) so that the final message tells the whole story. Servers use recover at the top so that one bad request cannot take the whole service down, and they log the problem instead.

Common mistakes

  • Ignoring the error with _. The program then goes on with a wrong or zero value.
  • Comparing error texts with == on strings. Use errors.Is or errors.As.
  • Using %v instead of %w in Errorf, which loses the original error.
  • Using panic for normal problems such as bad user input.
  • Calling recover outside a deferred function, where it does nothing.

Best practices

  • Check err != nil straight after the call and return early.
  • Add context with fmt.Errorf("doing X: %w", err).
  • Write error messages in lower case without a full stop, so they join well.
  • Keep panic and recover for the edges of the program.

Summary

Go functions return errors as values, and the caller checks err != nil. errors.New and fmt.Errorf create errors, %w wraps them, and errors.Is and errors.As look inside the chain. Custom error types carry extra data. panic is for bugs and impossible cases, and a deferred recover can turn a panic back into an error.

Quick check

1. What does a function return to say that it worked?
2. Which verb wraps an error inside another with fmt.Errorf?
3. What does errors.Is(err, ErrEmpty) do?
4. Where must recover be called to stop a panic?
5. When is panic a good choice?

Key takeaways

  • Go has no exceptions: a function that can fail returns an error as its last value, and the caller checks if err != nil.
  • Wrap errors with fmt.Errorf and %w, and test them with errors.Is and errors.As.
  • Use panic only for bugs; recover inside a deferred function can turn a panic back into an error.

Practice problems for this lesson

Was this lesson clear?

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.