liveBook · Manning

%w error verb

As explained in Go by Example

The %w error verb is a Go formatting directive that records an operand as the wrapped cause of a returned error.

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

How Go by Example covers it

How deep it goes
Explains wrapping and errors.Is through a worked parser example, without descending into error implementation internals.
Examples
Demonstrates contextual errors from a custom flag parser when strconv.Atoi rejects a flag value.
What you can do after
Diagnose errors with errors.Is while retaining informative command-line parsing context.
How it connects
Connects fmt.Errorf and errors.Is with strconv.Atoi and strconv.ErrSyntax.

Also explained in

Compare how 2 books explain %w error verb →

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.