TExcelTAD
Home › Go › Go Errors

Go Errors

Go has no exceptions. A function that can fail returns an error value as its last result, and the caller checks it right away. This makes failure paths visible in the code instead of hiding them in invisible jumps.

go
result, err := doSomething()
if err != nil {
	// handle or return the error
}
// use result

The error interface

error is a built-in interface with one method:

go
type error interface {
	Error() string
}

Any type with an Error() string method is an error. A nil error means "no failure".

Creating errors

Function Use for
errors.New("text") a fixed message
fmt.Errorf("format %v", x) a message with values
fmt.Errorf("context: %w", err) wrapping another error with extra context
go · try it yourself
package main

import (
	"errors"
	"fmt"
)

func withdraw(balance, amount int) (int, error) {
	if amount <= 0 {
		return balance, errors.New("amount must be positive")
	}
	if amount > balance {
		return balance, fmt.Errorf("insufficient funds: have %d, need %d", balance, amount)
	}
	return balance - amount, nil
}

func main() {
	balance := 100
	for _, amt := range []int{30, -5, 500, 70} {
		newBal, err := withdraw(balance, amt)
		if err != nil {
			fmt.Println("error:", err)
			continue
		}
		balance = newBal
		fmt.Println("ok, balance now", balance)
	}
}
ok, balance now 70
error: amount must be positive
error: insufficient funds: have 70, need 500
ok, balance now 0

Tip: Error messages start with a lower-case letter and have no trailing punctuation, because they are often joined into longer messages: open config: permission denied.

Sentinel errors and errors.Is

A sentinel error is a package-level error variable that callers can compare against. The standard library has many, like io.EOF. Because errors are often wrapped with %w to add context, compare with errors.Is, which looks through the whole wrap chain.

go · try it yourself
package main

import (
	"errors"
	"fmt"
)

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

var users = map[int]string{1: "ana", 2: "ben"}

func findUser(id int) (string, error) {
	name, ok := users[id]
	if !ok {
		return "", ErrNotFound
	}
	return name, nil
}

func loadProfile(id int) (string, error) {
	name, err := findUser(id)
	if err != nil {
		return "", fmt.Errorf("load profile %d: %w", id, err) // wrap
	}
	return "profile of " + name, nil
}

func main() {
	for _, id := range []int{2, 7} {
		p, err := loadProfile(id)
		switch {
		case errors.Is(err, ErrNotFound):
			fmt.Println("missing:", err)
		case err != nil:
			fmt.Println("other error:", err)
		default:
			fmt.Println(p)
		}
	}

	wrapped := fmt.Errorf("outer: %w", ErrNotFound)
	fmt.Println(wrapped == ErrNotFound, errors.Is(wrapped, ErrNotFound))
	fmt.Println(errors.Unwrap(wrapped) == ErrNotFound)
}
profile of ben
missing: load profile 7: not found
false true
true

Custom error types and errors.As

When callers need more than a message — a field name, an HTTP status, a retry hint — define your own error type. errors.As finds the first error in the chain of that type and gives it to you.

go · try it yourself
package main

import (
	"errors"
	"fmt"
)

type ValidationError struct {
	Field  string
	Reason string
}

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

func register(email string, age int) error {
	if email == "" {
		return &ValidationError{"email", "is required"}
	}
	if age < 13 {
		return &ValidationError{"age", fmt.Sprintf("must be at least 13, got %d", age)}
	}
	return nil
}

func main() {
	err := fmt.Errorf("signup failed: %w", register("kid@example.com", 9))
	fmt.Println(err)

	var ve *ValidationError
	if errors.As(err, &ve) {
		fmt.Println("field to highlight:", ve.Field)
	}

	fmt.Println(register("adult@example.com", 30) == nil)
}
signup failed: age: must be at least 13, got 9
field to highlight: age
true

Combining several errors

errors.Join bundles multiple errors into one — useful when validating many fields at once. errors.Is and errors.As still see each one.

go · try it yourself
package main

import (
	"errors"
	"fmt"
)

var ErrEmptyName = errors.New("name is empty")

func validate(name string, price float64) error {
	var errs []error
	if name == "" {
		errs = append(errs, ErrEmptyName)
	}
	if price < 0 {
		errs = append(errs, fmt.Errorf("price %.2f is negative", price))
	}
	return errors.Join(errs...) // nil if errs is empty
}

func main() {
	err := validate("", -3)
	fmt.Println(err)
	fmt.Println("---")
	fmt.Println(errors.Is(err, ErrEmptyName))
	fmt.Println(validate("Tea", 2) == nil)
}
name is empty
price -3.00 is negative
---
true
true

Error-handling guidelines

Do Avoid
Check every error right after the call Ignoring errors with _ without a reason
Add context while returning: fmt.Errorf("read %s: %w", path, err) Logging and returning the same error (it gets reported twice)
Compare with errors.Is / errors.As Comparing error strings
Return nil explicitly for success Returning a typed nil pointer as an error

Test yourself

Which verb in fmt.Errorf wraps an error so errors.Is can find it?

  1. %v
  2. %s
  3. %w
  4. %e

What does errors.As(err, &target) do?

  1. Converts any error to a string
  2. Finds an error of target's type in the chain and assigns it
  3. Compares two errors for equality
  4. Creates a new error

What does a nil error mean?

  1. An unknown error
  2. The operation succeeded
  3. The error was ignored
  4. A panic happened