Skip to content

Commit c9145e3

Browse files
committed
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.
1 parent 336204f commit c9145e3

1 file changed

Lines changed: 5 additions & 4 deletions

File tree

httpx/_models.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -791,7 +791,7 @@ def has_redirect_location(self) -> bool:
791791
and "Location" in self.headers
792792
)
793793

794-
def raise_for_status(self) -> Response:
794+
def raise_for_status(self, reason: str | None = None) -> Response:
795795
"""
796796
Raise the `HTTPStatusError` if one occurred.
797797
"""
@@ -807,13 +807,13 @@ def raise_for_status(self) -> Response:
807807

808808
if self.has_redirect_location:
809809
message = (
810-
"{error_type} '{0.status_code} {0.reason_phrase}' for url '{0.url}'\n"
810+
"{error_type} '{0.status_code} {0.reason_phrase}{extra_reason}' for url '{0.url}'\n"
811811
"Redirect location: '{0.headers[location]}'\n"
812812
"For more information check: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/{0.status_code}"
813813
)
814814
else:
815815
message = (
816-
"{error_type} '{0.status_code} {0.reason_phrase}' for url '{0.url}'\n"
816+
"{error_type} '{0.status_code} {0.reason_phrase}{extra_reason}' for url '{0.url}'\n"
817817
"For more information check: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/{0.status_code}"
818818
)
819819

@@ -825,7 +825,8 @@ def raise_for_status(self) -> Response:
825825
5: "Server error",
826826
}
827827
error_type = error_types.get(status_class, "Invalid status code")
828-
message = message.format(self, error_type=error_type)
828+
extra_reason = f' {reason}' if reason else ''
829+
message = message.format(self, error_type=error_type, extra_reason=extra_reason)
829830
raise HTTPStatusError(message, request=request, response=self)
830831

831832
def json(self, **kwargs: typing.Any) -> typing.Any:

0 commit comments

Comments
 (0)