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
ErrNegativeis a sentinel error made witherrors.New;RangeErroris a custom error type with its own message.checkreturnsnilfor a good value, aRangeErrorfor a number above 100 and a wrappedErrNegativefor a negative one.- In
main,errors.Isdetects the sentinel inside the wrapped error, anderrors.Aspulls out theRangeErrorso itsMaxfield can be read. strconv.Atoi("12x")returns an error, which is printed.safeDividedivides 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. Useerrors.Isorerrors.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 != nilstraight 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
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.