-
-
Couldn't load subscription status.
- Fork 9.6k
Description
Currently, when
Response.raise_for_status()
raises an
HTTPError
, the exception message includes the status code, reason, and URL as a string, but the exception object itself doesn't expose the status code or response object as easily accessible attributes for programmatic error handling.
Current behavior (from
models.py
lines 999-1026):
def raise_for_status(self):
"""Raises :class:HTTPError, if one occurred."""
http_error_msg = ""
if isinstance(self.reason, bytes):
# decode reason...
if 400 <= self.status_code < 500:
http_error_msg = f"{self.status_code} Client Error: {reason} for url: {self.url}"
elif 500 <= self.status_code < 600:
http_error_msg = f"{self.status_code} Server Error: {reason} for url: {self.url}"
if http_error_msg:
raise HTTPError(http_error_msg, response=self)
While the response is passed to the exception, users need to parse the error message string or access exception.response.status_code to get the status code programmatically.
What This Feature Will Solve
Better Error Handling: Developers can catch
HTTPError
and easily branch logic based on specific status codes (e.g., retry on 429, different handling for 401 vs 403) without string parsing
Cleaner Code: Direct attribute access (e.status_code) is more Pythonic than e.response.status_code or parsing strings
Consistency: Other exception types in Requests already expose relevant attributes directly (e.g.,
JSONDecodeError
has msg, doc, pos)
Backward Compatible: Adding attributes doesn't break existing code