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.
Adding context to errors in Go attaches a descriptive message without losing original technical details. It's like putting a sticky note on a broken part that explains what you were doing when it broke, while still keeping the part itself intact for inspection. You use this whenever a low-level operation fails and you need to explain the high-level context to the user or debugger.