Use the %w verb in fmt.Errorf to wrap errors, preserving the error chain for errors.Is and errors.As checks.
Use the %w verb in fmt.Errorf to wrap an existing error, enabling errors.Is and errors.As to traverse the error chain.
import "fmt"
func process() error {
if err := readFile(); err != nil {
return fmt.Errorf("failed to read file: %w", err)
}
return nil
}
This creates a new error that retains the original error as its cause, allowing you to check for the underlying error type later using errors.Is(err, target).
The %w verb acts like a label that attaches a new message to an existing error without hiding the original problem. It allows your code to trace back through a chain of errors to find the root cause, similar to how a doctor might trace symptoms back to a specific illness. Use it whenever you need to add context to an error while still being able to programmatically detect the original issue.