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


