Preserve exception chains in HTTPAdapter with explicit 'from' clause #7057
+419
−13
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Summary
This PR enhances exception handling in the
HTTPAdapterclass by preserving exception chains using Python's explicitfromclause. This change improves debugging and error traceability by maintaining the original exception context when wrapping or converting urllib3 exceptions to requests-specific exceptions.Changes Made
Core Changes (
src/requests/adapters.py)Modified 13 exception raise statements across two key methods:
get_connection_with_tls_context()- Preserves chain whenValueErroris converted toInvalidURLsend()- Preserves chains for the following exception conversions:LocationValueError→InvalidURLProtocolError/OSError→ConnectionErrorMaxRetryError(with various reasons) →ConnectTimeout,RetryError,ProxyError,SSLError, orConnectionErrorClosedPoolError→ConnectionError_ProxyError→ProxyError_SSLError→SSLErrorReadTimeoutError→ReadTimeout_InvalidHeader→InvalidHeaderTesting (
tests/test_adapters.py)Added comprehensive test coverage with 14 new test methods in a dedicated
TestExceptionChainingclass:__cause__attribute is properly set when exceptions are raisedBenefits
Testing
All new exception chaining behavior is covered by unit tests that verify:
__cause__attributeExample
Before:
After:
When an error occurs, users will now see the full exception chain in tracebacks, making it easier to diagnose issues.