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


