Errors in Go: Values, Wrapping, errors.Is and errors.As
Learn how Go reports failures with error values, sentinel and custom errors, wrapping with %w, inspecting with errors.Is and errors.As, and when panic and recover are appropriate.
In this lesson you will
- Return and check errors
- Wrap errors with context
- Use errors.Is and errors.As
- Use panic and recover carefully
About 28 minutes
When the code is wrong
A customer enters a tracking code that does not exist, a weight that is not a number, or a parcel that is already delivered. Go handles such failures without exceptions. A function that can fail returns an error as its last result, the caller checks it right away with if err != nil, and the error is an ordinary value that you can inspect, wrap with context and pass up. This feels repetitive at first, and the benefit is that every failure path is visible in the code.
The error type is an interface with one method, Error() string. The package errors makes simple ones with errors.New, and fmt.Errorf builds formatted ones. A sentinel error is a package-level variable such as ErrNotFound that callers compare against. When you pass an error up you usually wrap it to add context, with the verb %w in fmt.Errorf, which keeps the original inside. The function errors.Is(err, target) walks the chain of wrapped errors and tells you whether target is in it, and errors.As(err, &target) finds an error of a given type and gives you access to its fields. Custom error types carry extra data. A panic is for truly unexpected situations, such as a programming mistake, and it unwinds the stack running deferred functions; recover, called inside a deferred function, catches a panic and turns it into a normal flow.
| Tool | Use |
|---|---|
| errors.New(“text”) | A simple error value |
| fmt.Errorf(“lookup %s: %w”, code, err) | Add context and keep the cause |
| errors.Is(err, ErrNotFound) | Is this error, or anything it wraps, that sentinel? |
| errors.As(err, &target) | Find an error of a given type in the chain |
| panic / recover | Programming mistakes, and the boundary of a server |
package main
import (
"errors"
"fmt"
"strconv"
)
var ErrNotFound = errors.New("parcel not found")
type WeightError struct {
Input string
Err error
}
func (e *WeightError) Error() string { return fmt.Sprintf("bad weight %q: %v", e.Input, e.Err) }
func (e *WeightError) Unwrap() error { return e.Err }
var parcels = map[string]float64{"PK-1": 2.5, "PK-2": 0.4}
func find(code string) (float64, error) {
kg, ok := parcels[code]
if !ok {
return 0, fmt.Errorf("find %s: %w", code, ErrNotFound)
}
return kg, nil
}
func parseWeight(s string) (float64, error) {
kg, err := strconv.ParseFloat(s, 64)
if err != nil {
return 0, &WeightError{Input: s, Err: err}
}
if kg <= 0 {
return 0, &WeightError{Input: s, Err: errors.New("must be positive")}
}
return kg, 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() {
if kg, err := find("PK-1"); err == nil {
fmt.Println("found PK-1:", kg, "kg")
}
_, err := find("PK-9")
fmt.Println("error text:", err)
fmt.Println("errors.Is(err, ErrNotFound):", errors.Is(err, ErrNotFound), "| err == ErrNotFound:", err == ErrNotFound)
wrapped := fmt.Errorf("handling request 42: %w", err)
fmt.Println("two levels:", wrapped)
fmt.Println("still found through two wraps:", errors.Is(wrapped, ErrNotFound))
for _, in := range []string{"3.5", "abc", "-1"} {
kg, err := parseWeight(in)
var we *WeightError
if errors.As(err, &we) {
fmt.Printf("input %q: WeightError with Input=%q | message: %v\n", in, we.Input, err)
} else {
fmt.Printf("input %q: ok, %.1f kg\n", in, kg)
}
}
q, err := safeDivide(10, 2)
fmt.Println("safeDivide(10, 2):", q, err)
q, err = safeDivide(1, 0)
fmt.Println("safeDivide(1, 0):", q, "|", err)
}
found PK-1: 2.5 kg
error text: find PK-9: parcel not found
errors.Is(err, ErrNotFound): true | err == ErrNotFound: false
two levels: handling request 42: find PK-9: parcel not found
still found through two wraps: true
input "3.5": ok, 3.5 kg
input "abc": WeightError with Input="abc" | message: bad weight "abc": strconv.ParseFloat: parsing "abc": invalid syntax
input "-1": WeightError with Input="-1" | message: bad weight "-1": must be positive
safeDivide(10, 2): 5 <nil>
safeDivide(1, 0): 0 | recovered: runtime error: integer divide by zero
The lookup failed with the message “find PK-9: parcel not found”, which is the context we added, find PK-9, wrapped around the sentinel error. Comparing with == gave false, because the error we received is a new wrapped value, while errors.Is gave true, since it looks through the wrapping. That is the reason to use errors.Is instead of ==. A second wrap, “handling request 42: find PK-9: parcel not found”, still answers true to errors.Is, so you can add context at every level of the program and still recognise the original cause at the top.
The custom WeightError carries the input text and the underlying error, and its Unwrap method lets errors.Is and errors.As see through it. For the three inputs, “3.5” parsed fine, and “abc” and “-1” both produced a WeightError that errors.As could extract, so the caller can read its Input field, while the message shows the reason: the standard library’s parse error for “abc” and our own “must be positive” for “-1”. Callers choose between checking for a specific value with Is and extracting data with As.
The last two lines show panic and recover. safeDivide(10, 2) returned 5 and no error. Dividing 1 by 0 is a run-time panic in Go, and the deferred function caught it with recover and turned it into an ordinary error, “recovered: runtime error: integer divide by zero”, with the result zero. Use this at the boundary of a server, so that one bad request does not stop the whole program, and not as a general way to handle ordinary failures.
Check by hand: the sentinel is wrapped once with “find PK-9: ” in front, and a second time with “handling request 42: ” in front of that, which gives the printed text. 10 / 2 is 5, and 1 / 0 has no integer result, so the runtime panics with “integer divide by zero”.
Writing _ = f() or leaving out the check hides failures. Handle the error, return it or log it, and let linters such as go vet and staticcheck remind you.
A message such as “open config: permission denied” tells you what the program was doing. Use fmt.Errorf with %w at each layer, and let the top layer print the whole chain.
Every program in this lesson was built and run with Go 1.24 while the course was written. Go releases twice a year, so check go.dev for the current version and release notes.
Practice
Write a function that reads a number from a string and returns a custom error with the position of the first bad character. Wrap its error in a caller and check it with errors.As. Write a safe wrapper that recovers from a panic in a goroutine and logs it.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
What is the error type in Go?
- A string
- An integer
- An interface with an Error() string method
- A class
Any type with that method is an error.
What does %w do in fmt.Errorf?
- Prints a warning
- Wraps an error so that Is and As can find it
- Formats a width
- Makes the error fatal
It keeps the cause inside.
Why was err == ErrNotFound false?
- Go compares addresses wrongly
- The error was wrapped
- The sentinel changed
- Errors cannot be compared
Use errors.Is.
What does errors.As do?
- Finds an error of a type in the chain and extracts it
- Creates an error
- Prints an error
- Panics
We read WeightError.Input.
When is recover appropriate?
- At the boundary of a server or task, for unexpected panics
- For every error
- Never
- In loops
Ordinary failures are errors, not panics.
Summary
- Go functions return errors as values; check them immediately.
- Wrap with %w to add context; inspect with errors.Is and errors.As.
- Custom error types carry data and can unwrap.
- panic and recover are for unexpected failures, at boundaries.
Questions
Is if err != nil too repetitive?
It is explicit, and tools and helpers reduce the noise. Many Go programmers value that every failure path is visible in the code.
Should I panic in library code?
Rarely. Libraries should return errors. Panic is for programmer errors, such as an impossible state.
How do I join several errors?
errors.Join combines errors into one, and errors.Is and errors.As look through all of them. It needs Go 1.20 or later.
