Map HTTPCore exceptions (#1044)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Map HTTPCore exceptions * Expose new TimeoutException
authored by Florimond Manca · committed by GitHub · parent fab4279 · Browse files · 4 files·+192 added−38 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+192 added−38 removed
- tests:+40 added−0 removed
- other:+152 added−38 removed
Provenance
- Commit
bacc2d1- Tree
ad64640- Author
Florimond Manca <florimond.manca@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
fab4279
4 files changed+192 added−38 removed
modified:httpx/__init__.py+2 added
23 unmodified lines24 ResponseClosed,25 ResponseNotRead,26 StreamConsumed,27 StreamError,28+ TimeoutException,29 TooManyRedirects,30 WriteError,31 WriteTimeout,32 )48 unmodified lines81 "RequestNotRead",82 "StreamConsumed",83 "StreamError",84 "ProxyError",85+ "TimeoutException",86 "TooManyRedirects",87 "WriteError",88 "WriteTimeout",89 "URL",12 unmodified linesmodified:httpx/_client.py+36 added-27 removed
16 unmodified lines17 Timeout,18 UnsetType,19 )20 from ._content_streams import ContentStream21-from ._exceptions import HTTPError, InvalidURL, RequestBodyUnavailable, TooManyRedirects21+from ._exceptions import (22+ HTTPCORE_EXC_MAP,23+ HTTPError,24+ InvalidURL,25+ RequestBodyUnavailable,26+ TooManyRedirects,27+ map_exceptions,28+)29 from ._models import URL, Cookies, Headers, Origin, QueryParams, Request, Response30 from ._status_codes import codes31 from ._transports.asgi import ASGITransport32 from ._transports.wsgi import WSGITransport678 unmodified lines711 712 transport = self.transport_for_url(request.url)713 714 try:715+ with map_exceptions(HTTPCORE_EXC_MAP):708- (709- http_version,710- status_code,711- reason_phrase,712- headers,713- stream,714- ) = transport.request(715- request.method.encode(),716- request.url.raw,717- headers=request.headers.raw,718- stream=request.stream,719- timeout=timeout.as_dict(),720- )716+ (717+ http_version,718+ status_code,719+ reason_phrase,720+ headers,721+ stream,722+ ) = transport.request(723+ request.method.encode(),724+ request.url.raw,725+ headers=request.headers.raw,726+ stream=request.stream,727+ timeout=timeout.as_dict(),728+ )729 except HTTPError as exc:730 # Add the original request to any HTTPError unless731 # there'a already a request attached in the case of732 # a ProxyError.529 unmodified lines1262 1263 transport = self.transport_for_url(request.url)1264 1265 try:1266+ with map_exceptions(HTTPCORE_EXC_MAP):1258- (1259- http_version,1260- status_code,1261- reason_phrase,1262- headers,1263- stream,1264- ) = await transport.request(1265- request.method.encode(),1266- request.url.raw,1267- headers=request.headers.raw,1268- stream=request.stream,1269- timeout=timeout.as_dict(),1270- )1267+ (1268+ http_version,1269+ status_code,1270+ reason_phrase,1271+ headers,1272+ stream,1273+ ) = await transport.request(1274+ request.method.encode(),1275+ request.url.raw,1276+ headers=request.headers.raw,1277+ stream=request.stream,1278+ timeout=timeout.as_dict(),1279+ )1280 except HTTPError as exc:1281 # Add the original request to any HTTPError unless1282 # there'a already a request attached in the case of1283 # a ProxyError.267 unmodified linesmodified:httpx/_exceptions.py+114 added-11 removed
1+import contextlib2 import typing3 4 import httpcore5 22 unmodified lines28 29 30 # Timeout exceptions...31 31-ConnectTimeout = httpcore.ConnectTimeout32-ReadTimeout = httpcore.ReadTimeout33-WriteTimeout = httpcore.WriteTimeout34-PoolTimeout = httpcore.PoolTimeout32 33+class TimeoutException(HTTPError):34+ """35+ The base class for timeout errors.36 37+ An operation has timed out.38+ """39+40+41+class ConnectTimeout(TimeoutException):42+ """43+ Timed out while connecting to the host.44+ """45+46+47+class ReadTimeout(TimeoutException):48+ """49+ Timed out while receiving data from the host.50+ """51+52+53+class WriteTimeout(TimeoutException):54+ """55+ Timed out while sending data to the host.56+ """57+58+59+class PoolTimeout(TimeoutException):60+ """61+ Timed out waiting to acquire a connection from the pool.62+ """63+64+65 # Core networking exceptions...66 39-NetworkError = httpcore.NetworkError40-ReadError = httpcore.ReadError41-WriteError = httpcore.WriteError42-ConnectError = httpcore.ConnectError43-CloseError = httpcore.CloseError67 68+class NetworkError(HTTPError):69+ """70+ The base class for network-related errors.71 72+ An error occurred while interacting with the network.73+ """74+75+76+class ReadError(NetworkError):77+ """78+ Failed to receive data from the network.79+ """80+81+82+class WriteError(NetworkError):83+ """84+ Failed to send data through the network.85+ """86+87+88+class ConnectError(NetworkError):89+ """90+ Failed to establish a connection.91+ """92+93+94+class CloseError(NetworkError):95+ """96+ Failed to close a connection.97+ """98+99+100 # Other transport exceptions...101 48-ProxyError = httpcore.ProxyError49-ProtocolError = httpcore.ProtocolError102 103+class ProxyError(HTTPError):104+ """105+ An error occurred while proxying a request.106+ """107 108+109+class ProtocolError(HTTPError):110+ """111+ A protocol was violated by the server.112+ """113+114+115 # HTTP exceptions...116 117 118 class DecodingError(HTTPError):81 unmodified lines200 class CookieConflict(HTTPError):201 """202 Attempted to lookup a cookie by name, but multiple cookies existed.203 """204+205+206+@contextlib.contextmanager207+def map_exceptions(208+ mapping: typing.Mapping[typing.Type[Exception], typing.Type[Exception]]209+) -> typing.Iterator[None]:210+ try:211+ yield212+ except Exception as exc:213+ mapped_exc = None214+215+ for from_exc, to_exc in mapping.items():216+ if not isinstance(exc, from_exc):217+ continue218+ # We want to map to the most specific exception we can find.219+ # Eg if `exc` is an `httpcore.ReadTimeout`, we want to map to220+ # `httpx.ReadTimeout`, not just `httpx.TimeoutException`.221+ if mapped_exc is None or issubclass(to_exc, mapped_exc):222+ mapped_exc = to_exc223+224+ if mapped_exc is None:225+ raise226+227+ raise mapped_exc(exc) from None228+229+230+HTTPCORE_EXC_MAP = {231+ httpcore.TimeoutException: TimeoutException,232+ httpcore.ConnectTimeout: ConnectTimeout,233+ httpcore.ReadTimeout: ReadTimeout,234+ httpcore.WriteTimeout: WriteTimeout,235+ httpcore.PoolTimeout: PoolTimeout,236+ httpcore.NetworkError: NetworkError,237+ httpcore.ConnectError: ConnectError,238+ httpcore.ReadError: ReadError,239+ httpcore.WriteError: WriteError,240+ httpcore.CloseError: CloseError,241+ httpcore.ProxyError: ProxyError,242+ httpcore.ProtocolError: ProtocolError,243+}modified:tests/test_exceptions.py+40 added
1+from typing import Any2+3+import httpcore4 import pytest5 6 import httpx7+from httpx._exceptions import HTTPCORE_EXC_MAP8 9 10+def test_httpcore_all_exceptions_mapped() -> None:11+ """12+ All exception classes exposed by HTTPCore are properly mapped to an HTTPX-specific13+ exception class.14+ """15+ not_mapped = [16+ value17+ for name, value in vars(httpcore).items()18+ if isinstance(value, type)19+ and issubclass(value, Exception)20+ and value not in HTTPCORE_EXC_MAP21+ ]22+23+ if not_mapped:24+ pytest.fail(f"Unmapped httpcore exceptions: {not_mapped}")25+26+27+def test_httpcore_exception_mapping() -> None:28+ """29+ HTTPCore exception mapping works as expected.30+ """31+32+ # Make sure we don't just map to `NetworkError`.33+ with pytest.raises(httpx.ConnectError):34+ httpx.get("http://doesnotexist")35+36+ # Make sure it also works with custom transports.37+ class MockTransport(httpcore.SyncHTTPTransport):38+ def request(self, *args: Any, **kwargs: Any) -> Any:39+ raise httpcore.ProtocolError()40+41+ client = httpx.Client(transport=MockTransport())42+ with pytest.raises(httpx.ProtocolError):43+ client.get("http://testserver")44+45+46 def test_httpx_exceptions_exposed() -> None:47 """48 All exception classes defined in `httpx._exceptions`49 are exposed as public API.12 unmodified lines