| name | go-error-wrapping |
| description | Wrap 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
return nil, fmt.Errorf("read config failed: %v", err)
return nil, err
return nil, errors.New("read config: " + err.Error())
Key Rules
- Use
%w to wrap, not %v or %s
- Add meaningful context (file names, IDs, operations)
- Keep messages lowercase, no punctuation
- Preserve original error for type checking
Example Chain
func ProcessUser(id int) error {
cfg, err := ReadConfig("/etc/app.conf")
if err != nil {
return fmt.Errorf("process user %d: %w", id, err)
}
return nil
}