]> git.ipfire.org Git - thirdparty/httpx.git/commitdiff
Add Response.is_error (#574)
authorTom Christie <tom@tomchristie.com>
Sat, 30 Nov 2019 17:43:48 +0000 (17:43 +0000)
committerGitHub <noreply@github.com>
Sat, 30 Nov 2019 17:43:48 +0000 (17:43 +0000)
docs/compatibility.md
httpx/models.py
httpx/status_codes.py
tests/models/test_responses.py

index a95c12cdb573257f08b1f04f21d42f409e6d3d45..d652a0abe6f1a7674d388700f7b7a40a53b179e2 100644 (file)
@@ -14,6 +14,7 @@ to the API in our own documentation. The following exceptions apply:
 but also provide lower-cased versions for API compatibility with `requests`.
 * `stream=True`. - Streaming responses provide the `.stream()` and `.raw()` byte iterator interfaces, rather than the `.iter_content()` method and the `.raw` socket interface.
 * `.get`, `.delete`, `.head`, `.options` -  These methods do not support `files`, `data`, or `json` arguments. Use `.request` if you need to need to send data using these http methods.
+* We don't support `response.is_ok` since the naming is ambiguous there, and might incorrectly imply an equivalence to `response.status_code == codes.OK`. Instead we provide an `.is_error` property.
 
 ## Advanced Usage
 
index e703e2da4864f7ecb204f98210b2cf14b614bc6b..5469efcdb66925b9d749895b00bbbefc1919bb3e 100644 (file)
@@ -846,6 +846,10 @@ class Response:
 
         return self._decoder
 
+    @property
+    def is_error(self) -> bool:
+        return StatusCode.is_error(self.status_code)
+
     @property
     def is_redirect(self) -> bool:
         return StatusCode.is_redirect(self.status_code) and "location" in self.headers
@@ -861,11 +865,9 @@ class Response:
 
         if StatusCode.is_client_error(self.status_code):
             message = message.format(self, error_type="Client Error")
+            raise HTTPError(message, response=self)
         elif StatusCode.is_server_error(self.status_code):
             message = message.format(self, error_type="Server Error")
-        else:
-            message = ""
-        if message:
             raise HTTPError(message, response=self)
 
     def json(self, **kwargs: typing.Any) -> typing.Union[dict, list]:
index 3be26cafed44403f4586baa5cb4e69d4a9631bda..eda7c562d73daddafc4d71961b66fa746c636582 100644 (file)
@@ -49,6 +49,10 @@ class StatusCode(IntEnum):
             StatusCode.PERMANENT_REDIRECT,
         )
 
+    @classmethod
+    def is_error(cls, value: int) -> bool:
+        return 400 <= value <= 599
+
     @classmethod
     def is_client_error(cls, value: int) -> bool:
         return 400 <= value <= 499
index 012d2b747fa1e2caed2853d0c72ae29aedb47116..e7be48723e2a5143ef128f119db5c8897350b18b 100644 (file)
@@ -23,6 +23,7 @@ def test_response():
     assert response.reason_phrase == "OK"
     assert response.text == "Hello, world!"
     assert response.elapsed == datetime.timedelta(0)
+    assert not response.is_error
 
 
 def test_response_repr():