liveBook · Manning

Errors.Is

As explained in 100 Go Mistakes and How to Avoid Them

errors.Is is a Go standard-library function that reports whether an error chain contains a specified error value or matches it according to an Is method.

A common mistake is comparing a returned error with == after adding context. If the error wraps a sentinel with fmt.Errorf and %w, direct equality fails. errors.Is checks the requested value throughout the error chain, so wrapped errors remain matchable. section 7.4

Replace direct equality when errors may be wrapped

Problematic check:\nerr := query()\nif err != nil {\n if err == sql.ErrNoRows {\n // ...\n }\n}\n\nCorrect check:\nerr := query()\nif err != nil {\n if errors.Is(err, sql.ErrNoRows) {\n // ...\n }\n}\n\nUse == only when wrapping is not part of the error path; use errors.Is when fmt.Errorf with %w may add context. section 7.4

err := query()
if err != nil {
    if errors.Is(err, sql.ErrNoRows) {
        // ...
    } else {
        // ...
    }
}

Inspect the errors.Is replacement for a direct sentinel comparison. section 7.4

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Explains the equality failure, shows corrected Go code, and describes recursive unwrapping through the error chain.
Examples
Contrasts == and errors.Is when checking sql.ErrNoRows returned by a query.
What it assumes
Assumes familiarity with Go errors, sentinel values, fmt.Errorf, and the %w wrapping directive.
What you can do after
Diagnose failed sentinel checks and replace equality with errors.Is when returned errors may be wrapped.
How it connects
Connects error sentinels, error wrapping, fmt.Errorf, %w, and errors.As.

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 100 Go Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.