Skip to content
Myr

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

4 files+192 added−38 removed

modified:httpx/__init__.py+2 added
23 unmodified lines
24 ResponseClosed,25 ResponseNotRead,26 StreamConsumed,27 StreamError,28 TimeoutException,29 TooManyRedirects,30 WriteError,31 WriteTimeout,32)
48 unmodified lines
81 "RequestNotRead",82 "StreamConsumed",83 "StreamError",84 "ProxyError",85 "TimeoutException",86 "TooManyRedirects",87 "WriteError",88 "WriteTimeout",89 "URL",
12 unmodified lines
modified:httpx/_client.py+36 added-27 removed
16 unmodified lines
17 Timeout,18 UnsetType,19)20from ._content_streams import ContentStream21from ._exceptions import HTTPError, InvalidURL, RequestBodyUnavailable, TooManyRedirects21from ._exceptions import (22 HTTPCORE_EXC_MAP,23 HTTPError,24 InvalidURL,25 RequestBodyUnavailable,26 TooManyRedirects,27 map_exceptions,28)29from ._models import URL, Cookies, Headers, Origin, QueryParams, Request, Response30from ._status_codes import codes31from ._transports.asgi import ASGITransport32from ._transports.wsgi import WSGITransport
678 unmodified lines
711712 transport = self.transport_for_url(request.url)713714 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 lines
12621263 transport = self.transport_for_url(request.url)12641265 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 lines
modified:httpx/_exceptions.py+114 added-11 removed
1import contextlib2import typing34import httpcore5
22 unmodified lines
282930# Timeout exceptions...3131ConnectTimeout = httpcore.ConnectTimeout32ReadTimeout = httpcore.ReadTimeout33WriteTimeout = httpcore.WriteTimeout34PoolTimeout = httpcore.PoolTimeout3233class TimeoutException(HTTPError):34 """35 The base class for timeout errors.3637 An operation has timed out.38 """394041class ConnectTimeout(TimeoutException):42 """43 Timed out while connecting to the host.44 """454647class ReadTimeout(TimeoutException):48 """49 Timed out while receiving data from the host.50 """515253class WriteTimeout(TimeoutException):54 """55 Timed out while sending data to the host.56 """575859class PoolTimeout(TimeoutException):60 """61 Timed out waiting to acquire a connection from the pool.62 """636465# Core networking exceptions...6639NetworkError = httpcore.NetworkError40ReadError = httpcore.ReadError41WriteError = httpcore.WriteError42ConnectError = httpcore.ConnectError43CloseError = httpcore.CloseError6768class NetworkError(HTTPError):69 """70 The base class for network-related errors.7172 An error occurred while interacting with the network.73 """747576class ReadError(NetworkError):77 """78 Failed to receive data from the network.79 """808182class WriteError(NetworkError):83 """84 Failed to send data through the network.85 """868788class ConnectError(NetworkError):89 """90 Failed to establish a connection.91 """929394class CloseError(NetworkError):95 """96 Failed to close a connection.97 """9899100# Other transport exceptions...10148ProxyError = httpcore.ProxyError49ProtocolError = httpcore.ProtocolError102103class ProxyError(HTTPError):104 """105 An error occurred while proxying a request.106 """107108109class ProtocolError(HTTPError):110 """111 A protocol was violated by the server.112 """113114115# HTTP exceptions...116117118class DecodingError(HTTPError):
81 unmodified lines
200class CookieConflict(HTTPError):201 """202 Attempted to lookup a cookie by name, but multiple cookies existed.203 """204205206@contextlib.contextmanager207def 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 = None214215 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_exc223224 if mapped_exc is None:225 raise226227 raise mapped_exc(exc) from None228229230HTTPCORE_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
1from typing import Any23import httpcore4import pytest56import httpx7from httpx._exceptions import HTTPCORE_EXC_MAP8910def 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 ]2223 if not_mapped:24 pytest.fail(f"Unmapped httpcore exceptions: {not_mapped}")252627def test_httpcore_exception_mapping() -> None:28 """29 HTTPCore exception mapping works as expected.30 """3132 # Make sure we don't just map to `NetworkError`.33 with pytest.raises(httpx.ConnectError):34 httpx.get("http://doesnotexist")3536 # 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()4041 client = httpx.Client(transport=MockTransport())42 with pytest.raises(httpx.ProtocolError):43 client.get("http://testserver")444546def test_httpx_exceptions_exposed() -> None:47 """48 All exception classes defined in `httpx._exceptions`49 are exposed as public API.
12 unmodified lines