Skip to content
Tutorials Center
My learning

Topics

Lesson 62 of 147 ยท Errors

Custom Error Types

Learn to build custom error types in Go - struct errors with fields, pointer vs value receivers, Is, As and Unwrap methods, error codes and the typed nil pitfall that makes err != nil true.

Sentinel errors answer the question "which error was it?" with a fixed value. Many failures carry more information than a fixed value can hold: which field failed validation, what HTTP status the server answered, how long to wait before retrying. For those you create a custom error type: any type, usually a struct, with an Error() string method.

Because error is an interface, a custom error costs nothing special. You define a struct, add a method and return it. Callers then use errors.As (from Wrapping and Inspecting Errors) to pull the typed value out of an error chain and read its fields. This lesson shows how to design such types well, how pointer and value receivers change their behaviour, how to customize errors.Is, how to model error codes, and the "typed nil" trap that catches almost every Go programmer once.

A struct that implements error

The smallest custom error is a struct with fields and an Error method:

Go A validation error with fields

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The function's declared return type is error, but it returns *ValidationError. That is legal because *ValidationError has the right method. The caller sees an error, and errors.As recovers the concrete pointer type to read Field and Reason. Callers that do not care about the details just print the error.

Name the type with an Error suffix (ValidationError, ParseError) and variables of that type err or ve/pe. Sentinel values start with Err (ErrNotFound). The standard library follows both conventions: fs.PathError and fs.ErrNotExist.

Pointer or value receivers?

Both work, and both appear in the standard library: fs.PathError and strconv.NumError are structs returned as pointers, while syscall.Errno is a plain integer type with a value receiver. The choice changes two behaviours.

Comparison. Errors are compared with == in errors.Is. Value-receiver structs with comparable fields are equal when their contents are equal. Pointers are equal only when they point to the same value:

Go Value errors compare by content, pointer errors by identity

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Matching with errors.As. The type you pass to errors.As must be exactly the type that was returned: *ValidationError matches a returned &ValidationError{}, but not a returned ValidationError{} value. Mixing the two is a common source of "my errors.As never matches" bugs:

Go errors.As must use the same type that was returned

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Because MyErr has a value receiver, the method set of *MyErr also contains Error, so *MyErr also implements error, but the dynamic type stored in err is MyErr, so only the first lookup succeeds.

The practical advice: use pointer receivers for struct errors (as the standard library does for most), always return the pointer, and always look for the pointer with errors.As. Use value receivers for tiny comparable types such as integers or strings.

Wrapping a cause: the Unwrap method

A custom error often exists to describe an operation and keep the underlying cause. Give it an Unwrap() error method, and errors.Is and errors.As can continue down the chain:

Go A custom error that wraps its cause

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

errors.Is(err, fs.ErrNotExist) is true even though err is our own type, because errors.Is calls Unwrap to continue down the chain. The type names the operation (loading a config), and the cause stays inspectable. This is exactly how fs.PathError, strconv.NumError and exec.Error work.

Customizing errors.Is and errors.As

Normally errors.Is(err, target) compares with ==. If your error type has an Is(target error) bool method, errors.Is calls it as well. That lets two errors be "the same" even if they are different values, for instance matching by code and ignoring the message:

Go An Is method matches by category

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Here ErrNotFound is a template: only its Status matters. This pattern gives callers a readable errors.Is(err, ErrNotFound) while the error still carries a body and other details.

A sibling method, As(target any) bool, exists for rare conversions and is almost never needed. Define Is when you want category matching; skip As.

Error codes and kinds

Large programs often classify errors into a small set of kinds (not found, permission denied, invalid input, internal), so that a handler can map them to HTTP statuses or exit codes without a large switch over concrete types. A common design is a defined integer or string type that itself implements error, or a field of that type inside a struct:

Go A Kind field classifies errors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The handler does not need to know any concrete error type except *Error. Even when another layer wrapped the error with fmt.Errorf, errors.As finds it. This is a simplified version of a design used in large Go code bases. Do not build it before you need it: for a small program, a few sentinel errors are enough.

The typed nil trap

An interface value holds two things: a type and a value. It is nil only when both are empty. If a function returns a typed nil pointer as an error, the interface contains a type (*ValidationError) and a nil value, so it is not nil:

Go A nil pointer in an error is not nil (surprising on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The "broken" version reports err == nil as false even though the input was valid, so callers go down the failure path and may crash on err.Error() when it dereferences the nil pointer. The %T shows the culprit: a *main.ValidationError hides inside.

Two rules avoid this entirely:

  1. Functions that return error should return nil literally on success, never a variable of a concrete pointer type.
  2. Keep error variables typed as error, and only convert to a concrete type with errors.As when you need the fields.

Designing error types well

  • Return error, not your concrete type. func Parse() (*Result, *ParseError) invites the typed nil trap on the caller's side and cannot be combined with other error sources.
  • Put useful, structured data in fields, such as line numbers, keys and codes, and build the message from them in Error(). Do not parse messages.
  • Keep Error() cheap and safe. It is called whenever the error is printed or logged, possibly on a nil-ish partially filled struct; avoid panics.
  • Document the types you export. Exporting an error type makes it part of your API, just like wrapping a cause with %w does.
  • Prefer sentinels for "which", types for "what details". If callers only branch on identity, var ErrX = errors.New(...) is simpler than a type.
Go A parser error with a line number

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the only requirement for a type to be usable as an error?

    error is an interface with one method. Any type that has Error() string satisfies it, struct or not.
  2. 2. A function returns &MyErr{} through an error. Which errors.As target matches?

    The target type must be the same as the dynamic type in the error. A *MyErr was returned, so you look for *MyErr via a pointer to a *MyErr variable.
  3. 3. What does Unwrap() error on a custom error enable?

    errors.Is and errors.As walk the chain by calling Unwrap, so a custom error that exposes its cause stays transparent.
  4. 4. What is err == nil after var p *MyErr; var err error = p?

    An interface is nil only if both its type and its value are nil. Here the type is *MyErr, so err != nil. Return a literal nil instead.
  5. 5. Why give an error type an Is(target error) bool method?

    errors.Is calls the method, so two errors can match even when they are different values, for instance sharing a Status.

Summary

  • A custom error is any type with Error() string; structs let you carry fields such as the field name, operation, status or line.
  • Prefer pointer receivers for struct errors, return the pointer, and look it up with errors.As using a pointer-typed variable.
  • Add Unwrap() error so errors.Is and errors.As can see the underlying cause.
  • An Is(target error) bool method lets errors match by category rather than identity.
  • A Kind or code field helps map errors to HTTP statuses or exit codes in one place.
  • A nil pointer stored in an error is not nil: return a literal nil on success and keep error variables typed as error.

Next: panic and recover covers the failures that are not ordinary errors.