go-error-wrapping

Wrap errors with context using fmt.Errorf %w pattern

⭐2stars🔀0forks📁View on GitHub🕐Updated Dec 28, 2025

When & Why to Use This Skill

This Claude skill automates the implementation of Go's best practices for error handling using the fmt.Errorf %w pattern. It ensures that errors are wrapped with meaningful context while preserving the original error chain, which is essential for effective debugging and error type assertion in Go applications. By following idiomatic standards, it helps developers maintain clean, traceable, and professional codebases.

Use Cases

  • Scenario 1: Enhancing file system operations by wrapping 'file not found' or 'permission denied' errors with the specific file path and the high-level operation being performed.
  • Scenario 2: Maintaining error transparency in multi-layered architectures, such as passing a database connection error from the repository layer to the service layer with added business logic context.
  • Scenario 3: Standardizing error message formatting across a team to ensure all errors are lowercase and lack trailing punctuation, adhering to the official Go style guide.
  • Scenario 4: Refactoring legacy Go code that uses %v for errors to the modern %w verb to enable the use of errors.Is and errors.As for robust error checking.
namego-error-wrapping
descriptionWrap errors with context using fmt.Errorf %w pattern

Error Wrapping with %w

Pattern

Use fmt.Errorf with %w to add context while preserving the error chain.

CORRECT

func ReadConfig(path string) (*Config, error) {
    data, err := os.ReadFile(path)
    if err != nil {
        return nil, fmt.Errorf("read config %s: %w", path, err)
    }

    var cfg Config
    if err := json.Unmarshal(data, &cfg); err != nil {
        return nil, fmt.Errorf("parse config %s: %w", path, err)
    }

    return &cfg, nil
}

WRONG

// Bad: Loses error chain
return nil, fmt.Errorf("read config failed: %v", err)

// Bad: No context
return nil, err

// Bad: String concatenation
return nil, errors.New("read config: " + err.Error())

Key Rules

  1. Use %w to wrap, not %v or %s
  2. Add meaningful context (file names, IDs, operations)
  3. Keep messages lowercase, no punctuation
  4. Preserve original error for type checking

Example Chain

// Error flows up with context at each layer:
// "process user 123: read config /etc/app.conf: open /etc/app.conf: no such file or directory"

func ProcessUser(id int) error {
    cfg, err := ReadConfig("/etc/app.conf")
    if err != nil {
        return fmt.Errorf("process user %d: %w", id, err)
    }
    // use cfg...
    return nil
}