typestar

Wrapping with %w in Go

fmt.Errorf with %w adds context and keeps the original reachable.

var ErrNotFound = errors.New("not found")

func loadTour(slug string) error {
    if slug == "" {
        return fmt.Errorf("load tour: %w", ErrNotFound)
    }
    return nil
}

func handler(slug string) string {
    err := loadTour(slug)
    if err == nil {
        return "loaded"
    }
    wrapped := fmt.Errorf("handler: %w", err)
    return fmt.Sprintf("%v | inner=%v", wrapped, errors.Unwrap(wrapped))
}

How it works

  1. %w records the wrapped error; %v only formats it.
  2. Each layer adds what it knows, not a whole traceback.
  3. errors.Unwrap peels one layer back off.

Keywords and builtins used here

The run, in numbers

Lines
17
Characters to type
361
Tokens
84
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 50 seconds.

Type this snippet

Step 1 of 4 in Wrapping, step 4 of 15 in Errors.

← Previous Next →