Go to content
Web development

How to Use errors.Is and errors.As in Go

Go’s error is a minimal interface: any type with an Error() string method counts as an error. For years the standard library gave you errors.New and fmt.Errorf, both of which produced message-only errors, so the only way to match a specific failure was to compare error values directly with ==. That approach stopped working once code started wrapping errors with context.

The Go 2 error inspection proposal, which landed in Go 1.13, added errors.Is and errors.As to the standard library so you can match errors through a chain of wrapped failures. After reading this you will know when to reach for each function, how sentinel errors stay matchable after wrapping, and how to design error values that keep working as your code evolves.

Why direct equality breaks once an error is wrapped

When a function calls deeper code and the call fails, the function often wants to add its own context before returning. fmt.Errorf with the %w verb does that while preserving the original error: the returned error implements Unwrap(), which returns the wrapped operand, and if you use more than one %w verb, Unwrap returns a slice of all wrapped errors in order. The error inspection design specifies that errors.Is and errors.As follow the chain by repeatedly calling Unwrap.

Wrapping creates a new error value. If your repository returns ErrNotFound and your service layer wraps it with fmt.Errorf("getting user: %w", err), the value the caller receives is no longer equal to ErrNotFound. Comparing with == returns false even though the root cause is the same. That is the problem errors.Is and errors.As solve.

Wrapping with %v instead of %w is a different decision: the formatting looks the same, but the returned error does not implement Unwrap, so the original error is gone and later checks cannot see it. Use %v only when you want to discard the cause.

errors.Is matches sentinel errors through the chain

A sentinel error is a predefined error value for an expected condition, conventionally named ErrSomething and assigned to a package-level variable. The standard library uses this pattern for io.EOF and os.ErrNotExist. errors.Is is the intended replacement for == when matching sentinels: it walks the error chain and reports whether the error is equal to the target, either directly or through wrapping. An error also matches if it implements an Is(error) bool method that returns true, so types can override the default comparison.

A sentinel is no longer directly comparable once anything wraps it. Consider a database connection pool that exposes ErrPoolExhausted so callers can implement backoff. A caller that checks if err == pool.ErrPoolExhausted silently misses the error once the pool wraps it with context. The same caller using errors.Is(err, pool.ErrPoolExhausted) keeps working whether the pool returns the sentinel directly or wraps it two layers deep. This stability is the benefit: callers match against the same name, and you can add context anywhere in the chain without breaking them.

errors.As pulls out the structured error type

Sentinel errors identify a condition but carry no data. When callers need fields, codes, or the underlying network or filesystem error, you define a custom error type and extract it with errors.As. The function finds the first error in the chain whose type matches the target type, sets the target to its value, and returns true. The target must be a non-nil pointer to a type that implements error, or to an interface type; passing anything else panics.

A typical use is retry logic around network calls. Instead of matching on message text, you type-assert the chain for a known error type and read its fields. The standard library’s net.Error interface, which exposes Timeout() and Temporary(), is a common target. A retry loop that checks errors.As for a net.Error and inspects those methods tells a transient network timeout apart from a permanent failure, then decides whether to back off and retry.

errors.As compares types, not property values, so it will not tell you that a ValidationError has a specific field value. To match on a field value, the type must implement Is. And a custom error that wraps another error must implement Unwrap for errors.Is and errors.As to see past it, as Technical Feeder’s walkthrough demonstrates. Without Unwrap, the chain stops at the custom type.

Choosing sentinel errors over custom types for stability

When you choose between sentinels and custom types, you shape how your error values behave over time. A sentinel like ErrUserNotFound is a constant value, so it can never change meaning over time; it fits expected operational states that callers should check explicitly; it also suits API contract exposure and conditions that will never need extra data. A custom type with fields is right when callers need structured information such as a validation code or a failing field name.

The stable design rule is to expose sentinels sparingly. Anwarul Islam Rana’s guidance from twelve years of Go work is that errors.New, fmt.Errorf, and custom types cover roughly 95 percent of needs, and sentinels appear only when callers need to distinguish a condition, about three to five per domain. Every exported sentinel is part of your API surface: callers write errors.Is against it, so removing or renaming it later breaks them. Custom types carry the same commitment once you document that errors.As with your type is supported.

Keep the two mechanisms matched to their purpose. Use errors.Is for sentinel errors and errors.As for custom error types. Mixing them gives you the wrong result: errors.Is against a custom type with fields returns false unless the type is comparable or implements Is, and errors.As against a sentinel fails because the sentinel’s type is errors.errorString, not your type.

Putting it together in a service

You can see the pattern in a layered service. The repository layer returns domain errors, the service layer adds context with %w, and the HTTP handler turns the result into a response. In Rana’s layered example, the handler uses errors.As for a ValidationError to return a client error with the failing fields, and errors.Is for ErrUserNotFound to return a not-found response. Internal or database failures return 500 without leaking details to the client, since exposing the underlying message can reveal internal systems. Dan Gillis’s REST API notes follow the same shape: client errors carry a structured body, and server errors stay generic.

A payment processor shows the retry decision. Define TransientError and PermanentError types, wrap failures appropriately, and let the caller use errors.As to decide the action, as Gopal Agrawal’s example does: a transient error schedules a retry with backoff, a permanent error notifies the user. The transport layer stays out of it; the error type carries the meaning, and the caller applies its own policy.

Library code should define the error types and let callers decide how to handle them, while application code handles errors at boundaries such as HTTP handlers and CLI commands. A boundary is also the right place to log once. Logging at every layer and returning the error produces duplicate log lines; add context with %w through the layers and log the full chain at the handler.

Wrapping tradeoffs: what %w exposes and hides

Wrapping is opt-in by design. The proposal authors chose not to wrap errors passed to fmt.Errorf by default. Doing so would change a package’s exposed surface by revealing wrapped error types. Wrapping requires the explicit %w verb. That same concern applies to your own code. Indiscriminate wrapping lets callers reach into your implementation through errors.Is and errors.As, tying them to types you may not want to promise. If you want to hide implementation details, errors.Opaque returns an error with the same formatting as the original but one that does not match it and cannot be unwrapped, so programmatic inspection stops there.

The tradeoff is between debuggability and encapsulation. Wrapping with %w builds an error chain that preserves the root cause across layers, which is valuable for troubleshooting and for giving callers precise control. But every type you expose becomes part of the contract, so expose only the sentinels and custom types you intend to support, and keep internal wrapping private.

For more on the mechanics of returning errors and carrying context through layers, see returning errors as values and error wrapping and context. When you map errors to HTTP responses, handling Go errors in API services walks through the boundary decisions.

More in Web development Back to top ↑