Use fmt.Errorf with the %w verb to wrap Go errors and preserve the original error chain for debugging.
Wrap errors in Go by using fmt.Errorf with the %w verb to link the new error to the original one.
import "fmt"
func readFile(path string) error {
_, err := os.ReadFile(path)
if err != nil {
return fmt.Errorf("read file %s: %w", path, err)
}
return nil
}
This allows you to check the root cause later using errors.Is or errors.As.
Wrapping errors adds context to a problem without losing the original cause. Think of it like adding a note to a broken part before sending it back to the factory; you explain what you were doing, but the factory still sees the actual broken piece. This helps you trace exactly where and why something failed in your code.