errors.Is()
Start with errors.Is()
errors.Is checks whether an error matches a target, including by following supported wrapped-error chains.
What you’ll learn
- Explain the main purpose of errors.is().
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
Use sentinel error variables declared with errors.New to represent stable conditions such as ErrNotFound. Call errors.Is(err, ErrNotFound) rather than comparing formatted error messages.
Direct err == target cannot find a sentinel hidden inside a wrapped error. errors.Is can also honor an error type’s own Is method where applicable. It is intended for checking a condition, not extracting structured fields.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import (
"errors"
"fmt"
)
var ErrNotFound = errors.New("not found")
func fetch() error { return fmt.Errorf("fetch profile: %w", ErrNotFound) }
func main() {
err := fetch()
fmt.Println("Direct equality:", err == ErrNotFound)
fmt.Println("errors.Is:", errors.Is(err, ErrNotFound))
}
Output
Direct equality: false
errors.Is: trueTrace what the program does
The wrapper is not the same error value as ErrNotFound, so direct equality is false. errors.Is follows the wrapping relationship and returns true.
Avoid common mistakes
- Do not rely on text equality for stable error categorization.
- errors.Is answers whether a target matches; use errors.As to obtain a compatible concrete error type.
Try it yourself
Create an ErrPermission sentinel and wrap it twice. Check it with errors.Is and compare with direct equality.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced errors.Is() in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.