Skip to content

Exceptions

Request and Response exceptions

The most important exception classes in HTTPX are RequestError and HTTPStatusError.

The RequestError class is a superclass that encompasses any exception that occurs while issuing an HTTP request. These exceptions include a .request attribute.

try:
    response = httpx.get("https://www.example.com/")
except httpx.RequestError as exc:
    print(f"An error occured while requesting {exc.request.url!r}.")

The HTTPStatusError class is raised by response.raise_for_status() on 4xx and 5xx responses. These exceptions include both a .request and a .response attribute.

response = httpx.get("https://www.example.com/")
try:
    response.raise_for_status()
except httpx.HTTPStatusError as exc:
    print(f"Error response {exc.response.status_code} while requesting {exc.request.url!r}.")

There is also a base class HTTPError that includes both of these categories, and can be used to catch either failed requests, or 4xx and 5xx responses.

You can either use this base class to catch both categories...

try:
    response = httpx.get("https://www.example.com/")
    response.raise_for_status()
except httpx.HTTPError as exc:
    print(f"Error while requesting {exc.request.url!r}.")

Or handle each case explicitly...

try:
    response = httpx.get("https://www.example.com/")
    response.raise_for_status()
except httpx.RequestError as exc:
    print(f"An error occured while requesting {exc.request.url!r}.")
except httpx.HTTPStatusError as exc:
    print(f"Error response {exc.response.status_code} while requesting {exc.request.url!r}.")

The exception hierarchy

  • HTTPError
    • RequestError
      • TransportError
        • TimeoutException
          • ConnectTimeout
          • ReadTimeout
          • WriteTimeout
          • PoolTimeout
        • NetworkError
          • ConnectError
          • ReadError
          • WriteError
          • CloseError
        • ProtocolError
          • LocalProtocolError
          • RemoteProtocolError
        • ProxyError
        • UnsupportedProtocol
      • DecodingError
      • TooManyRedirects
    • HTTPStatusError
  • InvalidURL
  • CookieConflict
  • StreamError
    • StreamConsumed
    • ResponseNotRead
    • RequestNotRead
    • ResponseClosed

Exception classes

class httpx.HTTPError(message, *, request)

Base class for RequestError and HTTPStatusError.

Useful for try...except blocks when issuing a request, and then calling .raise_for_status().

For example:

try:
    response = httpx.get("https://www.example.com")
    response.raise_for_status()
except httpx.HTTPError as exc:
    print(f"HTTP Exception for {exc.request.url} - {exc}")
class httpx.RequestError(message, *, request)

Base class for all exceptions that may occur when issuing a .request().

class httpx.TransportError(message, *, request)

Base class for all exceptions that occur at the level of the Transport API.

All of these exceptions also have an equivelent mapping in httpcore.

class httpx.TimeoutException(message, *, request)

The base class for timeout errors.

An operation has timed out.

class httpx.ConnectTimeout(message, *, request)

Timed out while connecting to the host.

class httpx.ReadTimeout(message, *, request)

Timed out while receiving data from the host.

class httpx.WriteTimeout(message, *, request)

Timed out while sending data to the host.

class httpx.PoolTimeout(message, *, request)

Timed out waiting to acquire a connection from the pool.

class httpx.NetworkError(message, *, request)

The base class for network-related errors.

An error occurred while interacting with the network.

class httpx.ConnectError(message, *, request)

Failed to establish a connection.

class httpx.ReadError(message, *, request)

Failed to receive data from the network.

class httpx.WriteError(message, *, request)

Failed to send data through the network.

class httpx.CloseError(message, *, request)

Failed to close a connection.

class httpx.ProtocolError(message, *, request)

The protocol was violated.

class httpx.LocalProtocolError(message, *, request)

A protocol was violated by the client.

For example if the user instantiated a Request instance explicitly, failed to include the mandatory Host: header, and then issued it directly using client.send().

class httpx.RemoteProtocolError(message, *, request)

The protocol was violated by the server.

For exaample, returning malformed HTTP.

class httpx.ProxyError(message, *, request)

An error occurred while establishing a proxy connection.

class httpx.UnsupportedProtocol(message, *, request)

Attempted to make a request to an unsupported protocol.

For example issuing a request to ftp://www.example.com.

class httpx.DecodingError(message, *, request)

Decoding of the response failed, due to a malformed encoding.

class httpx.TooManyRedirects(message, *, request)

Too many redirects.

class httpx.HTTPStatusError(message, *, request, response)

The response had an error HTTP status of 4xx or 5xx.

May be raised when calling response.raise_for_status()

class httpx.InvalidURL(message)

URL is improperly formed or cannot be parsed.

class httpx.CookieConflict(message)

Attempted to lookup a cookie by name, but multiple cookies existed.

Can occur when calling response.cookies.get(...).

class httpx.StreamError(message)

The base class for stream exceptions.

The developer made an error in accessing the request stream in an invalid way.

class httpx.StreamConsumed()

Attempted to read or stream content, but the content has already been streamed.

class httpx.ResponseNotRead()

Attempted to access response content, without having called read() after a streaming response.

class httpx.RequestNotRead()

Attempted to access request content, without having called read().

class httpx.ResponseClosed()

Attempted to read or stream response content, but the request has been closed.