Errors · 3 MIN READ

Is compares, As extracts

Choose between errors.Is and errors.As without trial and error.

errors.Is asks whether anything in the chain equals a sentinel. errors.As asks whether anything in the chain is a particular type, and gives it to you so you can read its fields.

Sentinel when the caller only needs to know which kind of failure it was; typed error when the caller needs a detail, such as which field was invalid.

SEE THE IDEA

Identity and type answer different questions

  1. 01

    Identity

    go
    errors.Is(err, target)

    Does a matching cause exist?

  2. 02

    Type

    go
    errors.As(err, &typed)

    Can a matching error type be extracted?

  3. 03

    Chain

    go
    Unwrap() error

    Inspection follows wrapped causes

Inspect the error contract instead of parsing the human-readable message.

In practice

Use Is for sentinel conditions that callers branch on and As for structured details such as a status or path. Both can traverse wrapped errors. Declare the destination variable for As first and pass its address; pointer error types require a pointer-valued destination variable.

Watch out

Comparing Error() strings is brittle. Messages can change while the error identity and type remain stable.

Official reference ↗

Work through the exercise

go
var invalid *ValidationError
if errors.As(err, &invalid) {
	return invalid.Field
}
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.