ProgramGuru

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.

Visual explanation for errors isUse errors.Is to match sentinel causes.ErrNotFoundStep 1Wrap with %wStep 2Direct == is falseStep 3errors.Is is trueStep 4Use errors.Is to match sentinel causes.
Use errors.Is to match sentinel causes.

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: true

Trace 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

Why is errors.Is useful for wrapped errors?
Choose one answer. You can try again.

Answer and explanation

It follows the error chain to check a target

Correct. The wrapper is not the same error value as ErrNotFound, so direct equality is false.

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.

    Next lesson: errors.As() →