liveBook · Manning

Error wrapping

Error wrapping adds contextual information to an error while preserving access to the underlying error for later propagation or inspection.

How 3 Manning books explain it

100 Go Mistakes and How to Avoid Them

Error wrapping is the practice of attaching contextual information to an error while preserving the underlying error for propagation and inspection.

How it is used
Adds failure context or marks an error while propagating an underlying error that callers may inspect.
How deep it goes
Contrasts direct returns, custom types, %w, and %v, then traces a failed type check and its errors.As correction.
Examples
Uses coordinate-validation logs and a transaction HTTP handler whose wrapped transient error defeats a direct type switch.
What you can do after
Diagnose/debug with it by replacing failed direct type checks with errors.As and returning contextual errors without duplicate logging.

Read how 100 Go Mistakes and How to Avoid Them explains error wrapping →

Learn Go with Pocket-Sized Projects

A wrapped error is an error that retains an underlying error while adding contextual information for higher-level handling.

How it is used
Propagates errors from validation or other lower layers while preserving context for higher-level handling.
How deep it goes
Defines %w wrapping, demonstrates a validator, and tests identity with errors.Is without exploring deeper error internals.
Examples
Uses invalid word length, expected-versus-actual counts, fmt.Errorf, and table-driven validator tests.
What you can do after
Apply it via fmt.Errorf with %w and inspect the retained cause using errors.Is.

Read how Learn Go with Pocket-Sized Projects explains error wrapping →

Go by Example

Error wrapping is the practice of adding contextual information to an error while preserving the original error for later inspection.

How it is used
Adds actionable context to failures returned by a custom command-line flag parser.
How deep it goes
Demonstrates contextual wrapping with %w and inspection with errors.Is, without descending into error-interface internals.
Examples
Uses invalid flag values, strconv.ErrSyntax, and a complete custom flag parser.
What you can do after
Apply it via fmt.Errorf to add context while allowing callers to identify the underlying parsing error.

Read how Go by Example explains error wrapping →

Related concepts

These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.