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:
- Wrap a meaningful sentinel error with fmt.Errorf and %w when adding context. section 4.2.3 section 8.2.3
- Check for that sentinel with errors.Is at the point where a distinct response is needed. section 4.2.3 section 8.2.3
- Avoid direct equality when the returned error may have been wrapped. section 8.2.3


