Errors as values

An error in Go is an ordinary value of the interface type error, which has one method, Error() string. Nothing is thrown and nothing is caught: a function that can fail returns the error as its last result, and the caller decides what to do with it. That is enough to make failure part of the signature, and it is visible in every call.

Creating and returning errors

errors.New makes an error with a fixed message, and fmt.Errorf makes one with formatted details. A package-level variable such as ErrNegative is a sentinel: the caller can compare against it, which is how the standard library reports os.ErrNotExist and io.EOF.

package main import ( "errors" "fmt" "strconv" ) var ErrNegative = errors.New("negative number") func squareRoot(n float64) (float64, error) { if n < 0 { return 0, ErrNegative } return n, nil } func parseAge(s string) (int, error) { n, err := strconv.Atoi(s) if err != nil { return 0, fmt.Errorf("age %q: %w", s, err) } if n < 0 { return 0, fmt.Errorf("age %q: %w", s, ErrNegative) } return n, nil } func main() { if v, err := squareRoot(4); err == nil { fmt.Println("root of 4:", v) } for _, s := range []string{"42", "x", "-3"} { age, err := parseAge(s) if err != nil { fmt.Println("error:", err) continue } fmt.Println("age:", age) } }

go run values.go

root of 4: 4
age: 42
error: age "x": strconv.Atoi: parsing "x": invalid syntax
error: age "-3": negative number

The %w verb wraps the inner error instead of pasting its text, so the chain keeps both messages and the original value. The lesson on wrapping and the one on errors.Is and errors.As read that chain; here it is enough to see that the message of the outer error contains the message of the inner one.

A type with details

An error that carries data is a type with an Error method. The method is on a pointer receiver, so the value can be inspected with a type assertion, and a caller that needs the field rather than the message asks for it.

package main import ( "errors" "fmt" ) type ValidationError struct { Field string Value string } func (e *ValidationError) Error() string { return fmt.Sprintf("%s: invalid value %q", e.Field, e.Value) } func validate(name, email string) error { if name == "" { return &ValidationError{Field: "name", Value: name} } if email == "" { return &ValidationError{Field: "email", Value: email} } return nil } func main() { err := validate("Go", "") fmt.Println(err) var ve *ValidationError if errors.As(err, &ve) { fmt.Println("field:", ve.Field) } fmt.Println("same error:", errors.Is(validate("", ""), &ValidationError{Field: "name"})) }

go run custom.go

email: invalid value ""
field: email
same error: false

errors.As walks the chain until it finds a value of the requested type, which is why the second argument is a pointer to a variable of that type. The last line is false: two separately allocated errors are not the same value, and errors.Is compares values, not messages. A sentinel is a package-level variable for exactly this reason.

Calling a method on a nil error

An error variable that is nil has no value behind the interface, so calling Error on it panics. The test if err != nil is not a formality: it is what keeps this program from being written.

package main import "fmt" func main() { var err error fmt.Println("about to call a method on nil") fmt.Println(err.Error()) }

go build -trimpath -o nilerr nilerr.go
GOTRACEBACK=none ./nilerr 2>&1; echo status: $?

about to call a method on nil
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x49e16c]
status: 2

The panic is a nil pointer dereference, and the process exits with status 2. A nil error means success, so a function that returns one is telling its caller that there is nothing to inspect.

Exercises

  1. Return a sentinel error from a function of your own and test it with errors.Is. What changes if you return a new errors.New with the same text instead?
  2. Add a Code() int method to ValidationError and use it to choose the exit status of a program.
  3. Wrap an os.ErrNotExist with %w and with %v. Which one still answers true to errors.Is(err, os.ErrNotExist)?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What is the error type in Go?

    Answer

    An interface with the method Error() string

    Any type with Error() string satisfies error, and errors.New returns one implementation.

  2. Where does a function that can fail put its error?

    Answer

    As the last result

    The convention is value first, error last, and callers check it immediately.

  3. What does a nil error mean?

    Answer

    The call succeeded

    nil is the absence of an error, so success is err == nil.

  4. What does the %w verb do in fmt.Errorf?

    Answer

    It wraps the error so its chain is kept

    %w stores the inner error, which errors.Is and errors.As can then find.

  5. What does this program print? package main import ( "errors" "fmt" ) func main() { err := errors.New("boom") fmt.Println(err) }

    Answer

    boom

    Println calls the Error method of the value, which returns the message.

  6. What does this program print? package main import ( "errors" "fmt" ) var ErrBad = errors.New("bad") func f() error { return fmt.Errorf("reading config: %w", ErrBad) } func main() { fmt.Println(errors.Is(f(), ErrBad)) }

    Answer

    true

    %w keeps the sentinel in the chain, and errors.Is finds it.

  7. What does this program print? package main import "fmt" func f() error { return nil } func main() { if err := f(); err != nil { fmt.Println("failed") } else { fmt.Println("ok") } }

    Answer

    ok

    The returned error is nil, so the else branch runs.

  8. What happens when Error() is called on a nil error interface?

    Answer

    The program panics

    There is no value behind the interface, so the method call dereferences nil.

  9. Why is a sentinel error a package-level variable?

    Answer

    So callers can compare the same value

    errors.Is compares the value, and a new errors.New with the same text is a different value.

  10. What does errors.As do?

    Answer

    It finds an error of a given type in the chain

    errors.As walks the wrapped chain and stores the first matching value in the target.

The code on this page was run with go 1.26.10 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev

Banner image