Skip to content
Tutorials Center
My learning

Topics

Go Reference ยท Errors, I/O and Files

Go errors.Is() function

Reference for Go errors.Is: check whether an error or any error it wraps equals a target, how the chain is searched, custom Is methods and joined errors.

errors.Is(err, target) reports whether err, or any error it wraps, matches target. It replaces err == target, which stops working as soon as some function in between adds context with fmt.Errorf("...: %w", err).

The function walks the chain from the outside in. At each step it checks whether the error is equal to the target (using == when the type is comparable) or has an Is(target error) bool method that says yes; then it unwraps and continues. It also follows errors made by errors.Join and by fmt.Errorf with several %w verbs.

Go
if errors.Is(err, fs.ErrNotExist) {
	// the file or directory is missing, however deep the error was wrapped
}

Try it

Go Finding a sentinel in a chain

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Go A custom Is method

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Syntax

Go
func Is(err, target error) bool
Name Description
err The error to inspect. May be nil.
target The error you are looking for, usually a sentinel such as io.EOF.

Returns: true if some error in the tree of err matches target, false otherwise. If err and target are both nil the result is true; if only err is nil it is false.

Edge cases: if the error type is not comparable (for example a struct with a slice field), the == test is skipped instead of panicking, so only an Is method can match it.

Usage notes

  • Use Is for values, As for types. To find out which sentinel you got, call Is; to read fields of a custom error type, call errors.As().
  • Wrapping must use %w. fmt.Errorf("...: %v", err) only copies the text, so Is cannot see the original error.
  • Common targets in the standard library: io.EOF, fs.ErrNotExist, fs.ErrExist, fs.ErrPermission, context.Canceled, context.DeadlineExceeded, sql.ErrNoRows.
  • Is methods should be shallow. They compare only the error itself; the package does the unwrapping.
  • Pointer errors compare by address, value errors by contents. A custom type used as a sentinel is usually a pointer or a distinct named type.
  • Joined errors: errors.Is returns true if any branch of the tree matches.
  • Order matters little but cost does: the search is linear in the depth of the chain, so it is cheap for realistic errors.