Structs and Interfaces

Go Error Handling: errors.Is and errors.As

Errors are values in Go. Return them, add context with %w, and check them the right way.

  • Intermediate
  • 4 min read
  • 1 runnable example
What you'll learn
  • Returning errors
  • Wrapping with %w
  • errors.Is and errors.As
findUser(id)
findUser(1)"Ada", nil
findUser(7)wrapped ErrNotFound
findUser(-1)*ValidationError

Check the error, then continue

Go has no exceptions for ordinary failures. A function that can fail returns an error as its last value, and the caller checks whether it is nil.

ErrNotFound is a fixed error value that callers can compare against. %w wraps it with more context, and errors.Is still finds it inside the wrapped error. ValidationError is an error type with its own data, and errors.As extracts it.

Key points

  1. nil means success.
  2. %w wraps an error with more context.
  3. errors.Is finds an error inside a wrapped one.

Runnable Go example

Go
Run code →
main.go
package main

import (
	"errors"
	"fmt"
)

var ErrNotFound = errors.New("user not found")

type ValidationError struct {
	Field string
}

func (e *ValidationError) Error() string {
	return "invalid " + e.Field
}

func findUser(id int) (string, error) {
	if id <= 0 {
		return "", &ValidationError{Field: "id"}
	}
	if id != 1 {
		return "", fmt.Errorf("find user %d: %w", id, ErrNotFound)
	}
	return "Ada", nil
}

func main() {
	for _, id := range []int{1, 7, -1} {
		name, err := findUser(id)
		var validation *ValidationError
		switch {
		case err == nil:
			fmt.Println("found", name)
		case errors.Is(err, ErrNotFound):
			fmt.Println("missing:", err)
		case errors.As(err, &validation):
			fmt.Println("bad input:", validation.Field)
		}
	}
}
Get a Run button for this example Result of running the code
found Ada
missing: find user 7: user not found
bad input: id

Practice

Open the example in the online compiler, change a value or add a line, and predict the output before you run it. Then break the code on purpose and read the compiler's message.

Finished this lesson?

Mark it as learned to track your progress.

Practice with a challenge

Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.

All challenges