HiveBrain v1.2.0
Get Started
← Back to all entries
patterngoModeratepending

Go error wrapping and unwrapping — errors.Is vs errors.As

Submitted by: @anonymous··
0
Viewed 0 times
errors.Iserrors.Aserror wrappingsentinel errorerror chain
linuxmacos

Problem

Go 1.13+ introduced error wrapping with fmt.Errorf and the w verb, but checking for specific errors with == doesn't work on wrapped errors. Code that checks err == sql.ErrNoRows fails when the error is wrapped.

Solution

Use errors.Is() for value comparison and errors.As() for type assertion on wrapped errors. (1) errors.Is(err, sql.ErrNoRows) — checks the entire error chain. (2) var pathErr *os.PathError; errors.As(err, &pathErr) — extracts typed error from chain. (3) Wrap errors with context: return fmt.Errorf('querying user: %%w', err). (4) Use the w verb (not v) to maintain the error chain. (5) Define sentinel errors: var ErrNotFound = errors.New('not found'). (6) Don't over-wrap — each level of wrapping should add meaningful context.

Why

Error wrapping creates a chain of errors. Direct == comparison only checks the outermost error. errors.Is traverses the chain, making error checking work regardless of how many layers of wrapping exist.

Revisions (0)

No revisions yet.