Go Error Handling: Best Practices with Examples (errors.Is, As, %w)
In Go, an error is a normal value. A function that can fail returns an error as its last result, the caller checks if err != nil right after the call, and either handles it or returns it up with some context added. There are no exceptions and no try/catch. panic exists, but it’s for bugs, not for a missing file or bad input.
That’s the whole model. The rest of this post covers the tools around it: creating errors, wrapping them with %w, checking them with errors.Is and errors.As, and combining several with errors.Join. All the output below is from real runs on Go 1.26.
Returning and checking errors
error is a built-in interface with one method, Error() string. A function returns nil when it worked:
result, err := someFunction()
if err != nil {
return err
}
// use result
Check the error before you touch the other return values. When err isn’t nil, the other values are usually zero values and shouldn’t be trusted. And handle each error once: either log it or return it, not both, or the same failure shows up three times in your logs.
Creating errors: errors.New and fmt.Errorf
errors.New makes an error with a fixed message, and fmt.Errorf makes one with formatted text. When callers need to recognize a specific error, declare it once as a package-level variable. That’s called a sentinel error:
var ErrNotFound = errors.New("user not found")
func findUser(id int) (string, error) {
if id != 1 {
return "", ErrNotFound
}
return "rez", nil
}
The standard library does the same thing with io.EOF, sql.ErrNoRows and fs.ErrNotExist. I go deeper into naming and message style in effective error creation in Go.
When a caller needs more than “which error”, like the field that failed validation, make a custom error type. Any type with an Error() string method is an error:
type ValidationError struct {
Field string
Value string
}
func (e *ValidationError) Error() string {
return fmt.Sprintf("invalid %s: %q", e.Field, e.Value)
}
func parseAge(s string) (int, error) {
n, err := strconv.Atoi(s)
if err != nil {
return 0, &ValidationError{Field: "age", Value: s}
}
return n, nil
}
If strconv.Atoi and its error types are new to you, they’re covered in Go string to int with Atoi and Itoa.
Wrapping errors with %w
An error that just says user not found doesn’t tell you which call failed. Wrapping adds context while keeping the original error inside. Use the %w verb in fmt.Errorf:
func loadProfile(id int, age string) error {
if _, err := findUser(id); err != nil {
return fmt.Errorf("load profile %d: %w", id, err)
}
if _, err := parseAge(age); err != nil {
return fmt.Errorf("load profile %d: %w", id, err)
}
return nil
}
Calling loadProfile(7, "30") returns load profile 7: user not found. Each layer adds its own prefix, so a deep error reads like a short trace: handle request: load profile 7: user not found.
%v would give the same text but drops the original error. That matters for the next section.
Checking errors with errors.Is and errors.As
Once an error is wrapped, err == ErrNotFound stops working, because err is now the wrapper. errors.Is walks the chain for you:
err := loadProfile(7, "30")
fmt.Println(errors.Is(err, ErrNotFound), err == ErrNotFound)
true false
The same goes for the standard library. os.Open on a missing file returns open missing.txt: no such file or directory, and errors.Is(err, fs.ErrNotExist) is true.
If the error had been wrapped with %v instead, the chain is broken:
lost := fmt.Errorf("load: %v", ErrNotFound)
fmt.Println(errors.Is(lost, ErrNotFound)) // false
errors.As is the type version. It finds the first error in the chain that matches the target type and fills in your variable, so you can read its fields:
err = loadProfile(1, "thirty")
fmt.Println(err)
var ve *ValidationError
if errors.As(err, &ve) {
fmt.Println("field:", ve.Field)
}
load profile 1: invalid age: "thirty"
field: age
Use errors.Is to ask “is this that specific error?” and errors.As to ask “is there an error of this type, and what’s in it?”. Both appeared in Go 1.13, and they’re the reason to always wrap with %w unless you want to hide the cause on purpose.
Returning several errors with errors.Join
Validation often finds more than one problem at a time. Since Go 1.20, errors.Join combines several errors into one, and Is and As still see every one of them:
joined := errors.Join(
errors.New("name is empty"),
&ValidationError{Field: "age", Value: "-1"},
)
fmt.Println(joined)
fmt.Println(errors.As(joined, &ve), ve.Value)
name is empty
invalid age: "-1"
true -1
The message puts each error on its own line.
Panic, recover and cleanup
panic stops the normal flow and unwinds the stack. Use it for programmer mistakes that shouldn’t happen, like an impossible state or a nil map you forgot to make. For anything the caller could reasonably expect, like bad input, a missing row or a network timeout, return an error so the caller decides what to do:
// Avoid this
func process(data []byte) {
if len(data) == 0 {
panic("no data")
}
}
// Prefer this
func process(data []byte) error {
if len(data) == 0 {
return errors.New("no data")
}
return nil
}
Cleanup goes with defer, placed right after the error check so it runs on every return path:
f, err := os.Open("file.txt")
if err != nil {
return err
}
defer f.Close()
defer can also add context to every error a function returns, and recover inside a deferred function turns a panic back into an error at a boundary like an HTTP handler. Both are shown with real output in Go defer: how it works and common pitfalls.
My checklist for Go errors: return them, wrap with %w and a short lowercase prefix saying what you were doing, check with errors.Is or errors.As, never compare wrapped errors with ==, and keep panic for bugs. If you’re starting a new service, the same habits show up in the init() post, where setup that can fail belongs in a function that returns an error.
