liveBook · Manning

Error wrapping

As explained in 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.

Error wrapping preserves an underlying error while adding context for the layer that can decide how to handle it. In Go, propagate it with fmt.Errorf and the %w verb. section 5.1.3

Add context while validating a guess

A validator can retain a sentinel error while reporting expected and actual lengths: fmt.Errorf("expected %d, got %d, %w", solutionLength, len(guess), errInvalidWordLength). The caller can display the detailed message, while tests use errors.Is to identify the underlying error. section 5.1.3

err := myFunction()
if err != nil {
    return fmt.Errorf("an error occurred in myFunction: %w", err)
}

Use the compact pattern when propagating an error from a lower-level function. section 5.1.3

Listing 5.14 game.go: validateGuess method
// errInvalidWordLength is returned when 
// the guess has the wrong number of characters.
var errInvalidWordLength = fmt.Errorf("invalid guess, word doesn't have the ➥same number of characters as the solution") #1

// validateGuess ensures the guess is valid enough.
func (g *Game) validateGuess(guess []rune) error {
    if len(guess) != solutionLength {
        return fmt.Errorf("expected %d, got %d, %w",
            solutionLength, len(guess), errInvalidWordLength)
    }

    return nil
}

See a validator that wraps a specific invalid-length error with measured context. section 5.1.3

How Learn Go with Pocket-Sized Projects covers it

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 it assumes
Assumes familiarity with Go functions returning errors and teaches wrapping through a small validation function.
What you can do after
Apply it via fmt.Errorf with %w and inspect the retained cause using errors.Is.
How it connects
Connects error handling with error propagation, validation, sentinel errors, and unit testing.

Also explained in

Compare how 3 books explain error wrapping →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Go with Pocket-Sized Projects. The section links point to the parts of the book it draws on.