Skip to content
Myr

_exceptions.py

This file

Path

httpx/_exceptions.py

343 lines · 7.7 KiB · Python

Last changed by

Switch to explicit `typing.Optional` throughout (#2096)Michael Oliverbefore adoption14a1704

History of this file

Take it

1"""2Our exception hierarchy:34* HTTPError5  x RequestError6    + TransportError7      - TimeoutException8        · ConnectTimeout9        · ReadTimeout10        · WriteTimeout11        · PoolTimeout12      - NetworkError13        · ConnectError14        · ReadError15        · WriteError16        · CloseError17      - ProtocolError18        · LocalProtocolError19        · RemoteProtocolError20      - ProxyError21      - UnsupportedProtocol22    + DecodingError23    + TooManyRedirects24  x HTTPStatusError25* InvalidURL26* CookieConflict27* StreamError28  x StreamConsumed29  x StreamClosed30  x ResponseNotRead31  x RequestNotRead32"""33import contextlib34import typing3536if typing.TYPE_CHECKING:37    from ._models import Request, Response  # pragma: nocover383940class HTTPError(Exception):41    """42    Base class for `RequestError` and `HTTPStatusError`.4344    Useful for `try...except` blocks when issuing a request,45    and then calling `.raise_for_status()`.4647    For example:4849    ```50    try:51        response = httpx.get("https://www.example.com")52        response.raise_for_status()53    except httpx.HTTPError as exc:54        print(f"HTTP Exception for {exc.request.url} - {exc}")55    ```56    """5758    def __init__(self, message: str) -> None:59        super().__init__(message)60        self._request: typing.Optional["Request"] = None6162    @property63    def request(self) -> "Request":64        if self._request is None:65            raise RuntimeError("The .request property has not been set.")66        return self._request6768    @request.setter69    def request(self, request: "Request") -> None:70        self._request = request717273class RequestError(HTTPError):74    """75    Base class for all exceptions that may occur when issuing a `.request()`.76    """7778    def __init__(79        self, message: str, *, request: typing.Optional["Request"] = None80    ) -> None:81        super().__init__(message)82        # At the point an exception is raised we won't typically have a request83        # instance to associate it with.84        #85        # The 'request_context' context manager is used within the Client and86        # Response methods in order to ensure that any raised exceptions87        # have a `.request` property set on them.88        self._request = request899091class TransportError(RequestError):92    """93    Base class for all exceptions that occur at the level of the Transport API.94    """959697# Timeout exceptions...9899100class TimeoutException(TransportError):101    """102    The base class for timeout errors.103104    An operation has timed out.105    """106107108class ConnectTimeout(TimeoutException):109    """110    Timed out while connecting to the host.111    """112113114class ReadTimeout(TimeoutException):115    """116    Timed out while receiving data from the host.117    """118119120class WriteTimeout(TimeoutException):121    """122    Timed out while sending data to the host.123    """124125126class PoolTimeout(TimeoutException):127    """128    Timed out waiting to acquire a connection from the pool.129    """130131132# Core networking exceptions...133134135class NetworkError(TransportError):136    """137    The base class for network-related errors.138139    An error occurred while interacting with the network.140    """141142143class ReadError(NetworkError):144    """145    Failed to receive data from the network.146    """147148149class WriteError(NetworkError):150    """151    Failed to send data through the network.152    """153154155class ConnectError(NetworkError):156    """157    Failed to establish a connection.158    """159160161class CloseError(NetworkError):162    """163    Failed to close a connection.164    """165166167# Other transport exceptions...168169170class ProxyError(TransportError):171    """172    An error occurred while establishing a proxy connection.173    """174175176class UnsupportedProtocol(TransportError):177    """178    Attempted to make a request to an unsupported protocol.179180    For example issuing a request to `ftp://www.example.com`.181    """182183184class ProtocolError(TransportError):185    """186    The protocol was violated.187    """188189190class LocalProtocolError(ProtocolError):191    """192    A protocol was violated by the client.193194    For example if the user instantiated a `Request` instance explicitly,195    failed to include the mandatory `Host:` header, and then issued it directly196    using `client.send()`.197    """198199200class RemoteProtocolError(ProtocolError):201    """202    The protocol was violated by the server.203204    For example, returning malformed HTTP.205    """206207208# Other request exceptions...209210211class DecodingError(RequestError):212    """213    Decoding of the response failed, due to a malformed encoding.214    """215216217class TooManyRedirects(RequestError):218    """219    Too many redirects.220    """221222223# Client errors224225226class HTTPStatusError(HTTPError):227    """228    The response had an error HTTP status of 4xx or 5xx.229230    May be raised when calling `response.raise_for_status()`231    """232233    def __init__(234        self, message: str, *, request: "Request", response: "Response"235    ) -> None:236        super().__init__(message)237        self.request = request238        self.response = response239240241class InvalidURL(Exception):242    """243    URL is improperly formed or cannot be parsed.244    """245246    def __init__(self, message: str) -> None:247        super().__init__(message)248249250class CookieConflict(Exception):251    """252    Attempted to lookup a cookie by name, but multiple cookies existed.253254    Can occur when calling `response.cookies.get(...)`.255    """256257    def __init__(self, message: str) -> None:258        super().__init__(message)259260261# Stream exceptions...262263# These may occur as the result of a programming error, by accessing264# the request/response stream in an invalid manner.265266267class StreamError(RuntimeError):268    """269    The base class for stream exceptions.270271    The developer made an error in accessing the request stream in272    an invalid way.273    """274275    def __init__(self, message: str) -> None:276        super().__init__(message)277278279class StreamConsumed(StreamError):280    """281    Attempted to read or stream content, but the content has already282    been streamed.283    """284285    def __init__(self) -> None:286        message = (287            "Attempted to read or stream some content, but the content has "288            "already been streamed. For requests, this could be due to passing "289            "a generator as request content, and then receiving a redirect "290            "response or a secondary request as part of an authentication flow."291            "For responses, this could be due to attempting to stream the response "292            "content more than once."293        )294        super().__init__(message)295296297class StreamClosed(StreamError):298    """299    Attempted to read or stream response content, but the request has been300    closed.301    """302303    def __init__(self) -> None:304        message = (305            "Attempted to read or stream content, but the stream has " "been closed."306        )307        super().__init__(message)308309310class ResponseNotRead(StreamError):311    """312    Attempted to access streaming response content, without having called `read()`.313    """314315    def __init__(self) -> None:316        message = "Attempted to access streaming response content, without having called `read()`."317        super().__init__(message)318319320class RequestNotRead(StreamError):321    """322    Attempted to access streaming request content, without having called `read()`.323    """324325    def __init__(self) -> None:326        message = "Attempted to access streaming request content, without having called `read()`."327        super().__init__(message)328329330@contextlib.contextmanager331def request_context(332    request: typing.Optional["Request"] = None,333) -> typing.Iterator[None]:334    """335    A context manager that can be used to attach the given request context336    to any `RequestError` exceptions that are raised within the block.337    """338    try:339        yield340    except RequestError as exc:341        if request is not None:342            exc.request = request343        raise exc