fmt Errorf with %w

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).