From c9145e30efd76f78e9344b57b45413e3d58ec7da Mon Sep 17 00:00:00 2001 From: yihuang Date: Sun, 8 Jun 2025 14:28:42 +0800 Subject: [PATCH] feat: allow passing extra error message in raise_for_status this allows usgae of `rsp.raise_for_status(rsp.text)`, in many error response, the body contains more error messages. --- httpx/_models.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/httpx/_models.py b/httpx/_models.py index 2cc86321a4..4f916f85fc 100644 --- a/httpx/_models.py +++ b/httpx/_models.py @@ -791,7 +791,7 @@ def has_redirect_location(self) -> bool: and "Location" in self.headers ) - def raise_for_status(self) -> Response: + def raise_for_status(self, reason: str | None = None) -> Response: """ Raise the `HTTPStatusError` if one occurred. """ @@ -807,13 +807,13 @@ def raise_for_status(self) -> Response: if self.has_redirect_location: message = ( - "{error_type} '{0.status_code} {0.reason_phrase}' for url '{0.url}'\n" + "{error_type} '{0.status_code} {0.reason_phrase}{extra_reason}' for url '{0.url}'\n" "Redirect location: '{0.headers[location]}'\n" "For more information check: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/{0.status_code}" ) else: message = ( - "{error_type} '{0.status_code} {0.reason_phrase}' for url '{0.url}'\n" + "{error_type} '{0.status_code} {0.reason_phrase}{extra_reason}' for url '{0.url}'\n" "For more information check: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/{0.status_code}" ) @@ -825,7 +825,8 @@ def raise_for_status(self) -> Response: 5: "Server error", } error_type = error_types.get(status_class, "Invalid status code") - message = message.format(self, error_type=error_type) + extra_reason = f' {reason}' if reason else '' + message = message.format(self, error_type=error_type, extra_reason=extra_reason) raise HTTPStatusError(message, request=request, response=self) def json(self, **kwargs: typing.Any) -> typing.Any: