How to Wrap Errors in Go with %w

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.