Repository: encode/httpx

Issue:
Raise dedicated exception in `.raise_from_status()`
Refs #949, spun up from #1064.

Currently `Response.raise_from_status()` raises a generic `HTTPError` exception.

The problematic side is that it is not possible to catch it separately without also catching all exceptions originating from HTTPX (since `HTTPError` is the base exception class).

So we should probably introduce a dedicated exception class, namely something like `HTTPStatusError`.

_Note: there's an implementation of this in #869 but the PR also introduced some other changes (including renaming `HTTPError` to `RequestError` which is not really desirable as discussed in #1064)._


Discussion:
Hello there! Sounds like a good issue for starting contributing to httpx, so I'll work on it if you don't mind @florimondmanca 🙂
@frankie567 Please feel free to 🎉

Resolving patch:
diff --git a/httpx/__init__.py b/httpx/__init__.py
--- a/httpx/__init__.py
+++ b/httpx/__init__.py
@@ -10,6 +10,7 @@
     CookieConflict,
     DecodingError,
     HTTPError,
+    HTTPStatusError,
     InvalidURL,
     NetworkError,
     NotRedirectResponse,
@@ -66,6 +67,7 @@
     "CookieConflict",
     "DecodingError",
     "HTTPError",
+    "HTTPStatusError",
     "InvalidURL",
     "NetworkError",
     "NotRedirectResponse",
diff --git a/httpx/_exceptions.py b/httpx/_exceptions.py
--- a/httpx/_exceptions.py
+++ b/httpx/_exceptions.py
@@ -121,6 +121,17 @@ class DecodingError(HTTPError):
     """
 
 
+class HTTPStatusError(HTTPError):
+    """
+    Response sent an error HTTP status.
+    """
+
+    def __init__(self, *args: typing.Any, response: "Response") -> None:
+        super().__init__(*args)
+        self._request = response.request
+        self.response = response
+
+
 # Redirect exceptions...
 
 
diff --git a/httpx/_models.py b/httpx/_models.py
--- a/httpx/_models.py
+++ b/httpx/_models.py
@@ -23,7 +23,7 @@
 )
 from ._exceptions import (
     CookieConflict,
-    HTTPError,
+    HTTPStatusError,
     InvalidURL,
     NotRedirectResponse,
     RequestNotRead,
@@ -825,7 +825,7 @@ def is_redirect(self) -> bool:
 
     def raise_for_status(self) -> None:
         """
-        Raise the `HTTPError` if one occurred.
+        Raise the `HTTPStatusError` if one occurred.
         """
         message = (
             "{0.status_code} {error_type}: {0.reason_phrase} for url: {0.url}\n"
@@ -834,10 +834,10 @@ def raise_for_status(self) -> None:
 
         if StatusCode.is_client_error(self.status_code):
             message = message.format(self, error_type="Client Error")
-            raise HTTPError(message, response=self)
+            raise HTTPStatusError(message, response=self)
         elif StatusCode.is_server_error(self.status_code):
             message = message.format(self, error_type="Server Error")
-            raise HTTPError(message, response=self)
+            raise HTTPStatusError(message, response=self)
 
     def json(self, **kwargs: typing.Any) -> typing.Any:
         if self.charset_encoding is None and self.content and len(self.content) > 3:


Test patch:
diff --git a/tests/client/test_async_client.py b/tests/client/test_async_client.py
--- a/tests/client/test_async_client.py
+++ b/tests/client/test_async_client.py
@@ -98,7 +98,7 @@ async def test_raise_for_status(server):
             )
 
             if 400 <= status_code < 600:
-                with pytest.raises(httpx.HTTPError) as exc_info:
+                with pytest.raises(httpx.HTTPStatusError) as exc_info:
                     response.raise_for_status()
                 assert exc_info.value.response == response
             else:
diff --git a/tests/client/test_client.py b/tests/client/test_client.py
--- a/tests/client/test_client.py
+++ b/tests/client/test_client.py
@@ -106,7 +106,7 @@ def test_raise_for_status(server):
                 "GET", server.url.copy_with(path=f"/status/{status_code}")
             )
             if 400 <= status_code < 600:
-                with pytest.raises(httpx.HTTPError) as exc_info:
+                with pytest.raises(httpx.HTTPStatusError) as exc_info:
                     response.raise_for_status()
                 assert exc_info.value.response == response
                 assert exc_info.value.request.url.path == f"/status/{status_code}"