liveBook · Manning

Error wrapping

As explained in Go by Example

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

Error wrapping adds useful context while preserving the original error for later inspection. In a command-line flag parser, wrap conversion failures with the flag name and invalid value using fmt.Errorf and the %w verb. section 4.2.3

Wrapping a flag-value error

When setVar cannot parse a value, return fmt.Errorf("invalid value %q for flag -%s: %w", val, name, err). The resulting error identifies the bad input while retaining errors such as strconv.ErrSyntax for inspection with errors.Is(err, strconv.ErrSyntax). section 4.2.3

Listing 4.3 Flag parser (hit/cmd/hit/config.go)
package main

import (
    "fmt"
    "strings"
    . . .
)

type config struct {
    url string
    n   int
    c   int
    rps int
}

func parseArgs(c *config, args []string) error {
    flagSet := map[string]parseFunc{  #1
        "url": stringVar(&c.url),  #2
        "n":   intVar(&c.n),  #3
        "c":   intVar(&c.c),   #3
        "rps": intVar(&c.rps),   #3
    }

    for _, arg := range args {
        name, val, _ := strings.Cut(arg, "=")  #4
        name = strings.TrimPrefix(name, "-")  #5

        setVar, ok := flagSet[name]  #6
        if !ok {
           return fmt.Errorf(
                "flag provided but not defined: -%s",
                name,
            )
        }
        if err := setVar(val); err != nil { #7
            return fmt.Errorf(  #8
                "invalid value %q for flag -%s: %w",  #8
                val, name, err,   #8
            )   #8
        }
    }

    return nil
}

Inspect the complete flag parser to see error wrapping integrated with flag lookup, closures, configuration updates, and type-specific value parsers. section 4.2.3

How Go by Example covers it

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 it assumes
Builds on Go functions, closures, pointers, maps, and basic error handling while applying them in a parser.
What you can do after
Apply it via fmt.Errorf to add context while allowing callers to identify the underlying parsing error.
How it connects
Connects error wrapping with fmt.Errorf, errors.Is, strconv.Atoi, and command-line flag parsing.

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 Go by Example. The section links point to the parts of the book it draws on.