error#

error is a built-in interface that defines a single method:

type error interface {
    Error() string
}

Creating errors#

  • errors.New(text string): Creates an ad-hoc error.
  • fmt.Errorf(format string, a ...any) error
    • Use the %w verb to wrap an error (this automatically implements Unwrap).
    • Use %v to include the error message without wrapping.

Sentinel errors vs Ad-hoc errors#

  • Sentinel error: A predefined, static error (usually package-level) created with errors.New that has a fixed memory address.
  • Ad-hoc error: Dynamically created at the site of failure using errors.New.

Wrapping errors#

Error tree#

A series of wrapped errors forms an error tree. It is a tree (not chain) because errors.Join can wrap multiple errors into one.

Custom wrapping#

To wrap an error with a custom error type, your type must implement the Unwrap method. Usually, you do not call Unwrap directly; instead, use errors.Is and errors.As.

errors.Is and errors.As#

errors.Is#

errors.Is(err, target error) bool checks if an error tree contains a specific value.

  • Use errors.Is instead of == for comparison, as wrapped errors change the type.
  • It traverses the error tree calling Unwrap to find a match.
  • By default, it uses ==. If your error type is non-comparable, implement the Is method on your error.

errors.As#

errors.As(<err>, <target>) checks if an error tree contains a specific type.

The primary purpose of errors.As is to perform type assertions on wrapped errors. While a standard type assertion (if _, ok := err.(*MyErr)) only checks the outermost error, errors.As traverses the entire error tree to find a match.

  • Use if errors.As(err, &me) instead of type assertion (if _, ok := err.(*MyErr)) to find a specific type.
  • Like errors.Is, it traverses the error tree calling Unwrap internally to find a match.
  • If the Error() method uses a pointer receiver, the second argument must be a pointer-to-pointer.

eg.

type PointerError struct { Query string }
func (e *PointerError) Error() string { return e.Query }
var pErr *PointerError // The target type
errors.As(err, &pErr)  // &pErr is **PointerError

type ValueError struct { Code []int }
func (e ValueError) Error() string { return "error" }
var vErr ValueError
errors.As(err, &vErr)  // &vErr is *ValueError

The second parameter must be a pointer to an error or a pointer to an interface.

var ee *EmployeeError
if errors.As(err, &ee) {
  // do something with ee
}

errors.As is a function that “fills” a variable rather than just “reading” it. Therefore, it is perfectly normal and correct for the target pointer variable (ee) to be nil initially.

Because Go is a pass-by-value language (see Pointer), passing ee directly would only pass a copy of nil. To overwrite the memory address held by the caller’s pointer variable ee with the found error instance, you must pass the address of the pointer variable itself (&ee, which is **EmployeeError).


# go