errors.Is, errors.As and sentinel errors
A caller decides what to do with an error, and the decision needs to recognise it. Comparing with == only works for the exact value the function returned, which a wrapper breaks. errors.Is walks the chain looking for a match, and errors.As walks it looking for a type, filling a pointer with the first value that fits. The previous lesson built the chain; this one reads it.
errors.Is walks the chain
A sentinel is an error value exported by a package, and errors.Is(err, ErrNotFound) is true when the chain contains it. The check is not a string comparison: a freshly made errors.New("not found") is a different value with the same text and does not match. Under the hood Is compares with == at each layer, and the Is method on a custom error can extend the rule.
package main
import (
"errors"
"fmt"
)
var ErrNotFound = errors.New("not found")
func find(id int) error {
return fmt.Errorf("find %d: %w", id, ErrNotFound)
}
func main() {
err := find(7)
fmt.Println(err)
fmt.Println("errors.Is:", errors.Is(err, ErrNotFound))
fmt.Println("== :", err == ErrNotFound)
fresh := fmt.Errorf("not found")
fmt.Println("same text:", fresh, errors.Is(fresh, ErrNotFound))
}
go run is.go
find 7: not found
errors.Is: true
== : false
same text: not found false
The first check found the sentinel through the wrapper, and == on the wrapper failed because the dynamic type is the wrapper, not the sentinel. The last line is the one that keeps a codebase honest: text is for readers, identity is for decisions.
errors.As finds a type
errors.As takes the address of a variable of the wanted type and searches the chain for a value assignable to it, then fills the variable and returns true. Its target must be a non-nil pointer to an interface or a type that implements error, which is why the declaration is a pointer variable and the argument is its address.
package main
import (
"errors"
"fmt"
)
type ValidationError struct {
Field string
Msg string
}
func (e *ValidationError) Error() string {
return e.Field + ": " + e.Msg
}
var ErrNotFound = errors.New("not found")
func create(email string) error {
if email == "" {
return fmt.Errorf("create user: %w", &ValidationError{Field: "email", Msg: "empty"})
}
return fmt.Errorf("create user: %w", ErrNotFound)
}
func main() {
err := create("")
fmt.Println(err)
var ve *ValidationError
if errors.As(err, &ve) {
fmt.Println("field:", ve.Field, "message:", ve.Msg)
}
var missing *ValidationError
fmt.Println("is a validation error:", errors.As(err, &missing))
}
go run as.go
create user: email: empty
field: email message: empty
is a validation error: true
The second errors.As declared a different variable and reported false, because the error was a validation error and not the other kind. A program that needs a field from an error uses As and then reads it; a program that only needs to know the kind uses a sentinel and Is.
Several causes at once
errors.Join combines errors into one value whose text is the messages on separate lines and whose Unwrap returns all of them. A cleanup routine that closes three things reports every failure instead of the first one, and the caller tests each cause with errors.Is exactly as for a single chain.
package main
import (
"errors"
"fmt"
)
var (
ErrDisk = errors.New("disk full")
ErrQuota = errors.New("quota exceeded")
)
func main() {
err := errors.Join(ErrDisk, ErrQuota)
fmt.Println(err)
fmt.Println("disk:", errors.Is(err, ErrDisk))
fmt.Println("quota:", errors.Is(err, ErrQuota))
fmt.Println("other:", errors.Is(err, errors.New("disk full")))
}
go run join.go
disk full
quota exceeded
disk: true
quota: true
other: false
The third check failed because a new error with the same text is another value. Join is for independent failures, not for accumulating context: the message it prints has no shared prefix, so a caller that wants context wraps the join with fmt.Errorf and %w.
The one comparison that works
A custom error type whose fields are comparable compares by value, so two separately created values with the same fields are equal and errors.Is agrees. A type with a slice or a map field cannot be compared at all, and errors.Is on two such values panics on the comparison, which is one more reason to hang identity on sentinels and pointers.
package main
import (
"errors"
"fmt"
)
type coded struct {
code int
}
func (c coded) Error() string { return fmt.Sprintf("code %d", c.code) }
func main() {
a := coded{7}
b := coded{7}
fmt.Println("struct values equal:", a == b, "Is:", errors.Is(a, b))
x := errors.New("same text")
y := errors.New("same text")
fmt.Println("errors.New equal:", x == y, "Is:", errors.Is(x, y))
}
go run equal.go
struct values equal: true Is: true
errors.New equal: false Is: false
The struct values matched, and the two errors.New values did not, even though their text is identical. A sentinel is a singleton created once at package level, and that identity is the whole point of exporting it.
Exercises
- Wrap a sentinel twice and check it with errors.Is and with ==. Explain each result in one line.
- Define a TimeoutError with a duration field, return it wrapped from a function, and read the duration in the caller with errors.As.
- Join the errors of two failed cleanups and print the result. How many lines does the message have, and what does errors.Is return for each cause?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Why does == fail on a wrapped error?
Answer
The dynamic type is the wrapper, not the sentinel inside it
== compares the interface's dynamic type and value, and the wrapper is a different value.
-
What does this program print?
package main import ( "errors" "fmt" ) var ErrNotFound = errors.New("not found") func find(id int) error { return fmt.Errorf("find %d: %w", id, ErrNotFound) } func main() { err := find(7) fmt.Println(err) fmt.Println("errors.Is:", errors.Is(err, ErrNotFound)) fmt.Println("== :", err == ErrNotFound) fresh := fmt.Errorf("not found") fmt.Println("same text:", fresh, errors.Is(fresh, ErrNotFound)) }Answer
find 7: not found / errors.Is: true / == : false / same text: not found false
Is walks the chain and finds the sentinel, while == sees the wrapper and the fresh error is another value.
-
What must the target of errors.As be?
Answer
A non-nil pointer to a type or interface that implements error
As needs somewhere to store the value it finds, and it checks the target at run time.
-
What does the third line of this program print?
package main import ( "errors" "fmt" ) type ValidationError struct { Field string Msg string } func (e *ValidationError) Error() string { return e.Field + ": " + e.Msg } var ErrNotFound = errors.New("not found") func create(email string) error { if email == "" { return fmt.Errorf("create user: %w", &ValidationError{Field: "email", Msg: "empty"}) } return fmt.Errorf("create user: %w", ErrNotFound) } func main() { err := create("") fmt.Println(err) var ve *ValidationError if errors.As(err, &ve) { fmt.Println("field:", ve.Field, "message:", ve.Msg) } var missing *ValidationError fmt.Println("is a validation error:", errors.As(err, &missing)) }Answer
create user: email: empty / field: email message: empty / is a validation error: true
The variable was a different type from the one in the chain, so As reported false.
-
What does errors.Join produce?
Answer
One error whose message lists every cause and whose Unwrap returns all of them
Join keeps each cause reachable, so errors.Is works for every one.
-
What does the last line of this program print?
package main import ( "errors" "fmt" ) var ( ErrDisk = errors.New("disk full") ErrQuota = errors.New("quota exceeded") ) func main() { err := errors.Join(ErrDisk, ErrQuota) fmt.Println(err) fmt.Println("disk:", errors.Is(err, ErrDisk)) fmt.Println("quota:", errors.Is(err, ErrQuota)) fmt.Println("other:", errors.Is(err, errors.New("disk full"))) }Answer
disk full / quota exceeded / disk: true / quota: true / other: false
A new errors.New with the same text is a different value, so Is does not match it.
-
When do two custom error values compare equal with ==?
Answer
When their types are comparable and every field is equal
Value comparison follows the field types; slices and maps make a type uncomparable.
-
What does the last line of this program print?
package main import ( "errors" "fmt" ) type coded struct { code int } func (c coded) Error() string { return fmt.Sprintf("code %d", c.code) } func main() { a := coded{7} b := coded{7} fmt.Println("struct values equal:", a == b, "Is:", errors.Is(a, b)) x := errors.New("same text") y := errors.New("same text") fmt.Println("errors.New equal:", x == y, "Is:", errors.Is(x, y)) }Answer
struct values equal: true Is: true / errors.New equal: false Is: false
Two calls to errors.New make two distinct values, and the text plays no part in equality.
-
Which check should a caller use for a wrapped sentinel?
Answer
errors.Is
Is follows the chain; == only sees the outermost value and text matching is fragile.
-
What does the first line of this program print?
package main import ( "errors" "fmt" ) type coded struct { code int } func (c coded) Error() string { return fmt.Sprintf("code %d", c.code) } func main() { a := coded{7} b := coded{7} fmt.Println("struct values equal:", a == b, "Is:", errors.Is(a, b)) x := errors.New("same text") y := errors.New("same text") fmt.Println("errors.New equal:", x == y, "Is:", errors.Is(x, y)) }Answer
struct values equal: true Is: true / errors.New equal: false Is: false
coded has one comparable field, so both comparisons agree.
The code on this page was run with go 1.26.10 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev