Skip to content
Myr

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

4 files+72 added−31 removed

modified:httpx/backends/asyncio.py+24 added-18 removed
2 unmodified lines
3import typing45from ..config import Timeout6from ..exceptions import ConnectTimeout, ReadTimeout, WriteTimeout7from ..utils import as_network_error8from .base import BaseLock, BaseSemaphore, BaseSocketStream, ConcurrencyBackend910SSL_MONKEY_PATCH_APPLIED = False11
113 unmodified lines
125126 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 None135136 async def write(self, data: bytes, timeout: Timeout) -> None:
1 unmodified line
138 return139140 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 None149150 def is_connection_dropped(self) -> bool:
21 unmodified lines
172 # 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()178179180class AsyncioBackend(ConcurrencyBackend):181 def __init__(self) -> None:
10 unmodified lines
192 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()203204 return SocketStream(stream_reader=stream_reader, stream_writer=stream_writer)
7 unmodified lines
212 ) -> SocketStream:213 server_hostname = hostname if ssl_context else None214215 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()225226 return SocketStream(stream_reader=stream_reader, stream_writer=stream_writer)
42 unmodified lines
modified:httpx/backends/trio.py+19 added-7 removed
3 unmodified lines
4import trio56from ..config import Timeout7from ..exceptions import ConnectTimeout, ReadTimeout, WriteTimeout8from ..utils import as_network_error9from .base import BaseLock, BaseSemaphore, BaseSocketStream, ConcurrencyBackend101112def none_as_inf(value: typing.Optional[float]) -> float:
16 unmodified lines
29 self.stream, ssl_context=ssl_context, server_hostname=hostname30 )3132 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)3637 raise ConnectTimeout()38
8 unmodified lines
47 read_timeout = none_as_inf(timeout.read_timeout)4849 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)5354 raise ReadTimeout()5556 async def write(self, data: bytes, timeout: Timeout) -> None:
3 unmodified lines
60 write_timeout = none_as_inf(timeout.write_timeout)6162 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)6667 raise WriteTimeout()6869 def is_connection_dropped(self) -> bool:
26 unmodified lines
96 ) -> SocketStream:97 connect_timeout = none_as_inf(timeout.connect_timeout)9899 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)102103 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()107108 return SocketStream(stream=stream)109110 raise ConnectTimeout()111
6 unmodified lines
118 ) -> SocketStream:119 connect_timeout = none_as_inf(timeout.connect_timeout)120121 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)124125 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()129130 return SocketStream(stream=stream)131132 raise ConnectTimeout()133
43 unmodified lines
modified:httpx/exceptions.py+15 added-6 removed
69 unmodified lines
70 Decoding of the response failed.71 """727374# Network exceptions...757677class NetworkError(HTTPError):78 """79 A failure occurred while trying to access the network.80 """818283class ConnectionClosed(NetworkError):84 """85 Expected more data from peer, but connection was closed.86 """878889# Redirect exceptions...909192class RedirectError(HTTPError):
68 unmodified lines
161 URL was missing a hostname, or was not one of HTTP/HTTPS.162 """163164150class ConnectionClosed(HTTPError):151 """152 Expected more data from peer, but connection was closed.153 """154155165class CookieConflict(HTTPError):166 """167 Attempted to lookup a cookie by name, but multiple cookies existed.168 """
modified:httpx/utils.py+14 added
1import codecs2import collections3import contextlib4import logging5import netrc6import os7import re
4 unmodified lines
12from time import perf_counter13from types import TracebackType14from urllib.request import getproxies1516from .exceptions import NetworkError1718if typing.TYPE_CHECKING: # pragma: no cover19 from .models import PrimitiveData20 from .models import URL21
333 unmodified lines
355 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)359360361@contextlib.contextmanager362def 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