How to Add Context to Errors in Go

Use fmt.Errorf with the %w verb to wrap Go errors with context while maintaining the error chain for unwrapping.

Wrap the original error with fmt.Errorf and the %w verb to attach context while preserving the error chain.

if err != nil {
    return fmt.Errorf("failed to process tar archive: %w", err)
}

This allows you to unwrap the error later using errors.Is or errors.As to check for specific types like archive/tar.ErrInsecurePath.