The %w error verb records an operand as the wrapped cause of an error returned by fmt.Errorf. Add surrounding details without losing the original error. section 4.2.3
Add context while parsing flags
When a value parser fails, return fmt.Errorf("invalid value %q for flag -%s: %w", val, name, err). A caller can then test errors.Is(err, strconv.ErrSyntax) and respond specifically to the underlying conversion failure. 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 custom flag parser to see where the wrapped error is returned after a value parser fails. section 4.2.3

