Errors · 3 MIN READ

An error is any type with an Error method

Write an error that carries data the caller can read.

error is an interface with one method, so anything with Error() string is one. That is what makes an error able to carry structured information: a field for the line that failed, the value that was rejected, the operation that was attempted.

errors.As is the counterpart to errors.Is. Where Is asks "is this that particular error", As asks "is there an error of this type anywhere in the chain, and if so give it to me" — which is how a caller reads those fields back out after the error has been wrapped.

SEE THE IDEA

An error can carry structured information

  1. 01

    Data

    go
    type ParseError struct { Line int }

    Fields describe the failure

  2. 02

    Contract

    go
    Error() string

    Supplies the human-readable message

  3. 03

    Inspection

    go
    errors.As(err, &parseErr)

    Recovers the structured fields

The error interface is one method; behavior and metadata can live together.

In practice

Choose value or pointer receivers consistently with how the error will be returned and inspected. Keep Error free of side effects, because logging may call it more than once. An Unwrap method can expose a lower-level cause when that cause is part of the intended contract.

Watch out

Avoid returning a typed nil pointer as an error interface; the resulting interface is non-nil.

Official reference ↗

Work through the exercise

go
package main

// ParseError should report which field failed and why, and
// satisfy the error interface.
type ParseError struct {
	Field  string
	Reason string
}

// Parse returns a *ParseError when field is empty.
func Parse(field, value string) error {
	return nil
}

func main() {}
Try it yourself

Trace each value and write down your reasoning. Copy the source into GopherForge or your local Go environment to compile and check it. This web page does not execute your code or send it to a compiler service.

Progress stays in this browser. No account needed.