liveBook · Manning

Errors.Is

As explained in Go by Example

errors.Is is a Go standard-library function that reports whether an error or any error in its wrapping chain matches a target error.

errors.Is reports whether an error matches a target anywhere in its error chain. Use it when code adds context with fmt.Errorf and %w but callers still need to recognize a specific condition. section 4.2.3 section 4.8

A direct comparison only checks whether two error values are equal. Once an error is wrapped, compare with errors.Is instead: it searches the chain and returns true when the target error is present. This preserves useful context while allowing precise handling. section 8.2.3

Handle an invalid flag value

A flag parser can wrap strconv.ErrSyntax with a message that identifies the invalid flag value. After parsing fails, errors.Is(err, strconv.ErrSyntax) distinguishes a syntax failure from other errors, so the CLI can give a more informative response. section 4.2.3 section 4.8

err := fmt.Errorf(  #1
    "unexpected issue: %w", ErrBadRequest,   #1
)   #1
if errors.Is(err, ErrBadRequest) { . . . }  #2

This compact example wraps ErrBadRequest with context, then tests the resulting chain with errors.Is. The equivalent err == ErrBadRequest comparison would miss the wrapped target. section 8.2.3

Use errors.Is as part of an error-handling contract:

How Go by Example covers it

How deep it goes
Explains chain matching through %w-based wrapping and contrasts it with failing direct equality.
Examples
Uses wrapped strconv.ErrSyntax in a flag parser and wrapped ErrBadRequest in an in-memory link service.
What it assumes
Assumes familiarity with Go error returns and introduces wrapped error-chain matching through examples.
What you can do after
Apply it via the standard library to branch on wrapped sentinel errors without discarding context.
How it connects
Connects error chains, fmt.Errorf, sentinel errors, strconv.ErrSyntax, and command-line flag parsing.

Also explained in

Compare how 3 books explain errors.Is →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go by Example. The section links point to the parts of the book it draws on.