Wrapping and Inspecting Errors in Go

Add context to errors with %w, check them with errors.Is and errors.As, and return several at once with errors.Join.

A bare error like no such file or directory says what broke but not where or why. Wrapping lets each function add a short note while keeping the original error intact, and inspection lets code further up recognize that original error no matter how many notes were added. This section covers both sides.

Wrapping Errors with %w

fmt.Errorf("read settings: %w", err) adds context and keeps a link to err. %v prints the same text but drops that link.

err := fmt.Errorf("start app: %w", fmt.Errorf("read settings: %w", osErr))
// start app: read settings: open settings.json: no such file or directory

%v breaks error checks silently:

Messages built with %v look identical in logs, but errors.Is and errors.As can no longer see the original error.

errors.Is and errors.As

errors.Is(err, fs.ErrNotExist) checks whether a known error value is anywhere in the chain. errors.As(err, &pathErr) finds an error of a given type and gives you its fields. Both replace == and string matching, which break once errors are wrapped.

Combining Errors with errors.Join

errors.Join(errs...) returns all collected errors as one value, or nil when the list is empty. It fits form validation, batch jobs and cleanup code, and errors.Is still finds each error inside.

Summary

Wrap with %w to add context, inspect with errors.Is for values and errors.As for types, and join when several independent things fail together. These three tools keep messages readable for humans and checks reliable for code.

Wrapping Errors with %w in Go

How to add context to an error with fmt.Errorf and %w, the difference between %w and %v, and how errors.Unwrap walks the chain.

errors.Is and errors.As in Go

How to check which error happened with errors.Is, how to pull a typed error out of a chain with errors.As, and why == on errors stops working.

Combining Errors with errors.Join in Go

How to report several errors at once with errors.Join, how errors.Is and errors.As search joined errors, and when to return many errors instead of the first one.