Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Go Error Handling: errors.Is, errors.As, Sentinel Errors, and Custom Types

errors.Is and errors.As explained through the wrapping that makes them necessary: %w chains, multiple wrapped errors, custom Is methods, and the pointer rules that make As panic.

~4 min readGo
#Go#Error Handling#Backend
Layered error capsules scanned to reveal a sentinel error core inside

An error in Go is a value, and handling one well is mostly a question of what you compare it against. errors.Is asks "is this error, or anything it wraps, that sentinel?" and errors.As asks "does this chain contain a value of that type, so I can read its fields?" Before Go 1.13 the same checks were string comparisons and type assertions on the outermost error, which broke the moment anyone added context with fmt.Errorf. The two functions exist to make wrapping transparent, and they only work if the wrapping used %w.

Quick Summary

  • error is an interface with one method, Error() string. Any type with it is an error, including a struct with fields, which a string cannot carry.
  • Sentinel errors are package-level values (var ErrNotFound = errors.New("not found")) meant to be compared, not printed.
  • fmt.Errorf("...: %w", err) keeps the chain; %v copies the message and destroys it. Since Go 1.20 a single Errorf can wrap several errors with multiple %w verbs.
  • Use errors.Is for identity, errors.As for type and data. == only works while nothing has wrapped the error.
  • The target of errors.As must be a non-nil pointer: var e *QueryError; errors.As(err, &e). Passing the value, or a pointer to the wrong type, panics.
  • errors.Unwrap walks one link, errors.Join (1.20) merges independent errors into a tree, and both Is and As traverse the whole tree.
  • An error type can define Is(target error) bool (and As) to answer matches itself, which is how wrapped errors compare by code rather than by pointer.

Basic syntax and type signatures

go
var ( ErrNotFound = errors.New("not found") ErrForbidden = errors.New("forbidden") ) // A typed error carries data a sentinel cannot. type ValidationError struct { Field string Rule string } func (e *ValidationError) Error() string { return fmt.Sprintf("validation failed: %s violates %s", e.Field, e.Rule) } func load(id string) (User, error) { raw, err := os.ReadFile("data/" + id + ".json") if err != nil { // %w keeps the chain: errors.Is(err, fs.ErrNotExist) still works. return User{}, fmt.Errorf("load user %s: %w", id, err) } if len(raw) == 0 { return User{}, fmt.Errorf("load user %s: %w", id, ErrNotFound) } var u User if err := json.Unmarshal(raw, &u); err != nil { return User{}, fmt.Errorf("decode user %s: %w", id, err) } return u, nil } func handler(id string) error { u, err := load(id) switch { case errors.Is(err, fs.ErrNotExist), errors.Is(err, ErrNotFound): return nil // treat as absent case err != nil: return fmt.Errorf("handler: %w", err) } _ = u return nil } func annotate(err error) error { var ve *ValidationError if errors.As(err, &ve) { return fmt.Errorf("field %q: %w", ve.Field, err) } return err }

The switch order is the practical rule: test nil last or first depending on your style, but test specific sentinels before a generic err != nil, because once you return the generic error the specific case is gone.

Comparison and traversal side by side

FunctionQuestionTargetFollows wrapping
err == ErrXis it exactly that valuecomparable error valueno
errors.Is(err, ErrX)is it or does it wrap that valuevalue, and Is methods honouredyes, all branches
errors.As(err, &target)does the chain hold that typenon-nil pointer to error type or interfaceyes, all branches
errors.Unwrap(err)one level down—one link only
errors.Join(a, b)merge independent errors—creates Unwrap() []error
err.Error() == "..."text match—no, and brittle

errors.Is does not simply call ==. It walks the chain, and at each node it first checks for an Is(error) bool method on the node, then falls back to equality when the target's type is comparable. That method is what lets an error compare equal to a sentinel without holding the sentinel's pointer.

Practical edge cases and deep dives

1. A custom Is for errors that carry a code

go
type QueryError struct { Code int Op string } func (e *QueryError) Error() string { return fmt.Sprintf("%s: code %d", e.Op, e.Code) } var ErrConflict = errors.New("conflict") // Is lets errors.Is(err, ErrConflict) match any QueryError with code 409, // even after the error has been wrapped several times. func (e *QueryError) Is(target error) bool { if target == ErrConflict { return e.Code == http.StatusConflict } return false } func main() { err := fmt.Errorf("save: %w", &QueryError{Code: 409, Op: "insert"}) fmt.Println(errors.Is(err, ErrConflict)) // true }

This is the pattern that keeps a package's API stable: callers depend on ErrConflict, not on the numeric code, and a later change from 409 to another representation only touches the Is method. The method must not call errors.Is on itself, or the walk recurses; it receives the target and answers directly.

2. errors.As with pointers, interfaces, and the panic

go
type Timeout interface{ Timeout() bool } func classify(err error) string { // Type target: pointer to a struct that implements error. var ve *ValidationError if errors.As(err, &ve) { return "validation:" + ve.Field } // Interface target: pointer to an interface, matches by method set. var t Timeout if errors.As(err, &t) { return fmt.Sprintf("timeout:%v", t.Timeout()) } // A pointer to the error interface matches every non-nil error. var anyErr error if errors.As(err, &anyErr) { return "some error: " + anyErr.Error() } return "none" }

errors.As assigns the first match into the pointer's target and stops. Three mistakes account for nearly every panic at this call: passing ve instead of &ve (Go 1.21+ reports "errors: target must be a non-nil pointer to either a type that implements error, or to any interface type"), declaring var ve ValidationError and passing &ve when Error() has a pointer receiver (the type does not implement error, so the panic fires), and reusing one target across several As calls while assuming it holds the last match — it holds the first, because the walk stops there.

3. Multiple %w, errors.Join, and reporting several failures

go
func (v *Validator) Check(in Input) error { var errs []error if in.Name == "" { errs = append(errs, &ValidationError{Field: "name", Rule: "required"}) } if in.Email == "" { errs = append(errs, &ValidationError{Field: "email", Rule: "required"}) } return errors.Join(errs...) // nil when errs is empty } func save(in Input) error { if err := validate(in); err != nil { // Both wrapped errors stay reachable through the tree. return fmt.Errorf("save: %w", err) } if err := store(in); err != nil { return fmt.Errorf("save: %w", err) } return nil } // Later, one check finds the first validation failure: var ve *ValidationError if errors.As(saveErr, &ve) { /* ve.Field is "name" */ }

errors.Join returns nil when every argument is nil, which is why it can be the last statement of a validator without a length check. Its Error() method joins the messages with newlines, and Unwrap() []error makes Is and As fan out over every branch, so a single errors.As finds the first validation error in declaration order. Since Go 1.20, fmt.Errorf with more than one %w builds the same shape, which is useful when one step fails for two independent reasons.

4. Wrapping at the boundary without leaking internal types

go
// Internal detail: drivers return *pgconn.PgError. func repo(ctx context.Context, id string) (User, error) { var u User err := db.QueryRow(ctx, "select ...", id).Scan(&u.ID, &u.Name) if err != nil { if pgErr, ok := err.(*pgconn.PgError); ok && pgErr.Code == "23505" { return User{}, fmt.Errorf("insert user: %w", ErrConflict) } return User{}, fmt.Errorf("select user %s: %w", id, err) } return u, nil }

The boundary translates one vocabulary into another: the driver's error code becomes ErrConflict, and everything else is wrapped with enough context to locate the call in a log without losing the original. Callers above the repository never import the driver's package, and the repository does not need a custom Is method because it already returns the sentinel it wants to be matched on. Wrapping the same error twice with the same message prefix is the sign this translation is missing — the log then reads save: insert user: select user u1: ... with three layers that all say who was doing what.

Common mistakes and compiler errors

SymptomCauseFix
errors.Is is false after wrappingthe wrap used %v or errors.New(err.Error())use %w
x.(*MyErr) fails after wrappingassertion only sees the outermost errorerrors.As
panic: target must be a non-nil pointererrors.As(err, target) instead of &targetpass the address
panic: target must implement errorstruct with a pointer-receiver Error() passed by valuepass &value
errors.As matches the wrong errorvar e error; errors.As(err, &e) matches anythingassert the concrete type you need
errors.Is(err, err) true but nothing else matchescomparing an error to itself by accidentcompare against the sentinel
wrap disappears at the top levelhandler returned errors.New(fmt.Sprint(err))return err or wrap with %w
%w with a nil errorfmt.Errorf("x: %w", nil) yields a non-nil errorcheck err != nil first

The habit that prevents most of these is to decide, at each function boundary, whether the caller needs to recognise the failure or merely to report it. Recognition means %w and a sentinel; reporting means any format that reads well. Mixing the two — wrapping with %w and then also matching on err.Error() — produces code that works until a message changes, which is the failure mode errors.Is was introduced to end.

Try matching browser tools

All tools

Small utilities that fit Go work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Go guides

More in Go

All Go guides

The guides filed next to this one in Go, in library order.