Wrap network errors in HTTPX-specific exceptions (#707)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Florimond Manca · committed by Tom Christie · parent e19bd9b · Browse files · 4 files·+72 added−31 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+72 added−31 removed
- other:+72 added−31 removed
Provenance
- Commit
e1afbfa- Tree
7dd4206- Author
Florimond Manca <florimond.manca@gmail.com>- Committer
Tom Christie <tom@tomchristie.com>- Parent
e19bd9b
4 files changed+72 added−31 removed
modified:httpx/backends/asyncio.py+24 added-18 removed
2 unmodified lines3 import typing4 5 from ..config import Timeout6 from ..exceptions import ConnectTimeout, ReadTimeout, WriteTimeout7+from ..utils import as_network_error8 from .base import BaseLock, BaseSemaphore, BaseSocketStream, ConcurrencyBackend9 10 SSL_MONKEY_PATCH_APPLIED = False11 113 unmodified lines125 126 async def read(self, n: int, timeout: Timeout) -> bytes:127 try:128 async with self.read_lock:129+ with as_network_error(OSError):128- return await asyncio.wait_for(129- self.stream_reader.read(n), timeout.read_timeout130- )130+ return await asyncio.wait_for(131+ self.stream_reader.read(n), timeout.read_timeout132+ )133 except asyncio.TimeoutError:134 raise ReadTimeout() from None135 136 async def write(self, data: bytes, timeout: Timeout) -> None:1 unmodified line138 return139 140 try:141 async with self.write_lock:142+ with as_network_error(OSError):140- self.stream_writer.write(data)141- return await asyncio.wait_for(142- self.stream_writer.drain(), timeout.write_timeout143- )143+ self.stream_writer.write(data)144+ return await asyncio.wait_for(145+ self.stream_writer.drain(), timeout.write_timeout146+ )147 except asyncio.TimeoutError:148 raise WriteTimeout() from None149 150 def is_connection_dropped(self) -> bool:21 unmodified lines172 # This is fine, though, because '.close()' schedules the actual closing of the173 # stream, meaning that at best it will happen during the next event loop174 # iteration, and at worst asyncio will take care of it on program exit.175 async with self.write_lock:176+ with as_network_error(OSError):173- self.stream_writer.close()177+ self.stream_writer.close()178 179 180 class AsyncioBackend(ConcurrencyBackend):181 def __init__(self) -> None:10 unmodified lines192 ssl_context: typing.Optional[ssl.SSLContext],193 timeout: Timeout,194 ) -> SocketStream:195 try:196+ with as_network_error(OSError):192- stream_reader, stream_writer = await asyncio.wait_for( # type: ignore193- asyncio.open_connection(hostname, port, ssl=ssl_context),194- timeout.connect_timeout,195- )197+ stream_reader, stream_writer = await asyncio.wait_for( # type: ignore198+ asyncio.open_connection(hostname, port, ssl=ssl_context),199+ timeout.connect_timeout,200+ )201 except asyncio.TimeoutError:202 raise ConnectTimeout()203 204 return SocketStream(stream_reader=stream_reader, stream_writer=stream_writer)7 unmodified lines212 ) -> SocketStream:213 server_hostname = hostname if ssl_context else None214 215 try:216+ with as_network_error(OSError):211- stream_reader, stream_writer = await asyncio.wait_for( # type: ignore212- asyncio.open_unix_connection(213- path, ssl=ssl_context, server_hostname=server_hostname214- ),215- timeout.connect_timeout,216- )217+ stream_reader, stream_writer = await asyncio.wait_for( # type: ignore218+ asyncio.open_unix_connection(219+ path, ssl=ssl_context, server_hostname=server_hostname220+ ),221+ timeout.connect_timeout,222+ )223 except asyncio.TimeoutError:224 raise ConnectTimeout()225 226 return SocketStream(stream_reader=stream_reader, stream_writer=stream_writer)42 unmodified linesmodified:httpx/backends/trio.py+19 added-7 removed
3 unmodified lines4 import trio5 6 from ..config import Timeout7 from ..exceptions import ConnectTimeout, ReadTimeout, WriteTimeout8+from ..utils import as_network_error9 from .base import BaseLock, BaseSemaphore, BaseSocketStream, ConcurrencyBackend10 11 12 def none_as_inf(value: typing.Optional[float]) -> float:16 unmodified lines29 self.stream, ssl_context=ssl_context, server_hostname=hostname30 )31 32 with trio.move_on_after(connect_timeout):33+ with as_network_error(trio.BrokenResourceError):32- await ssl_stream.do_handshake()34+ await ssl_stream.do_handshake()35 return SocketStream(ssl_stream)36 37 raise ConnectTimeout()38 8 unmodified lines47 read_timeout = none_as_inf(timeout.read_timeout)48 49 with trio.move_on_after(read_timeout):50 async with self.read_lock:51+ with as_network_error(trio.BrokenResourceError):49- return await self.stream.receive_some(max_bytes=n)52+ return await self.stream.receive_some(max_bytes=n)53 54 raise ReadTimeout()55 56 async def write(self, data: bytes, timeout: Timeout) -> None:3 unmodified lines60 write_timeout = none_as_inf(timeout.write_timeout)61 62 with trio.move_on_after(write_timeout):63 async with self.write_lock:64+ with as_network_error(trio.BrokenResourceError):61- return await self.stream.send_all(data)65+ return await self.stream.send_all(data)66 67 raise WriteTimeout()68 69 def is_connection_dropped(self) -> bool:26 unmodified lines96 ) -> SocketStream:97 connect_timeout = none_as_inf(timeout.connect_timeout)98 99 with trio.move_on_after(connect_timeout):100+ with as_network_error(OSError):96- stream: trio.SocketStream = await trio.open_tcp_stream(hostname, port)101+ stream: trio.SocketStream = await trio.open_tcp_stream(hostname, port)102+103 if ssl_context is not None:104 stream = trio.SSLStream(stream, ssl_context, server_hostname=hostname)105+ with as_network_error(trio.BrokenResourceError):99- await stream.do_handshake()106+ await stream.do_handshake()107+108 return SocketStream(stream=stream)109 110 raise ConnectTimeout()111 6 unmodified lines118 ) -> SocketStream:119 connect_timeout = none_as_inf(timeout.connect_timeout)120 121 with trio.move_on_after(connect_timeout):122+ with as_network_error(OSError):114- stream: trio.SocketStream = await trio.open_unix_socket(path)123+ stream: trio.SocketStream = await trio.open_unix_socket(path)124+125 if ssl_context is not None:126 stream = trio.SSLStream(stream, ssl_context, server_hostname=hostname)127+ with as_network_error(trio.BrokenResourceError):117- await stream.do_handshake()128+ await stream.do_handshake()129+130 return SocketStream(stream=stream)131 132 raise ConnectTimeout()133 43 unmodified linesmodified:httpx/exceptions.py+15 added-6 removed
69 unmodified lines70 Decoding of the response failed.71 """72 73 74+# Network exceptions...75+76+77+class NetworkError(HTTPError):78+ """79+ A failure occurred while trying to access the network.80+ """81+82+83+class ConnectionClosed(NetworkError):84+ """85+ Expected more data from peer, but connection was closed.86+ """87+88+89 # Redirect exceptions...90 91 92 class RedirectError(HTTPError):68 unmodified lines161 URL was missing a hostname, or was not one of HTTP/HTTPS.162 """163 164 150-class ConnectionClosed(HTTPError):151- """152- Expected more data from peer, but connection was closed.153- """154-155-165 class CookieConflict(HTTPError):166 """167 Attempted to lookup a cookie by name, but multiple cookies existed.168 """modified:httpx/utils.py+14 added
1 import codecs2 import collections3+import contextlib4 import logging5 import netrc6 import os7 import re4 unmodified lines12 from time import perf_counter13 from types import TracebackType14 from urllib.request import getproxies15 16+from .exceptions import NetworkError17+18 if typing.TYPE_CHECKING: # pragma: no cover19 from .models import PrimitiveData20 from .models import URL21 333 unmodified lines355 def elapsed(self) -> timedelta:356 if self.end is None:357 return timedelta(seconds=perf_counter() - self.start)358 return timedelta(seconds=self.end - self.start)359+360+361+@contextlib.contextmanager362+def as_network_error(*exception_classes: type) -> typing.Iterator[None]:363+ try:364+ yield365+ except BaseException as exc:366+ for cls in exception_classes:367+ if isinstance(exc, cls):368+ raise NetworkError(exc) from exc369+ raise