Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,9 @@ Prefer a single auth middleware (`AsyncMiddleware` for async clients,
- If the API has a structured error body, model it as a dataclass and raise a
typed exception carrying it.
- Reuse the built-in exceptions where they fit:
`unihttp.exceptions.{ClientError, ServerError, HTTPStatusError, NetworkError, RequestTimeoutError}`.
`unihttp.exceptions.{ClientError, ServerError, HTTPStatusError, NetworkError, RequestTimeoutError, NonRetryableError, UniHTTPError}`.
- Retry only `NetworkError` and `RequestTimeoutError`; `NonRetryableError` fails
the same way on every attempt.

## Pagination

Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ httpx2 = ["httpx2>=2.0.0"]
requests = ["requests>=2.32.0"]
aiohttp = ["aiohttp>=3.10.0"]
niquests = ["niquests>=3.17.0"]
zapros = ["zapros>=0.11.0"]
zapros = ["zapros>=0.12.0"]
pydantic = ["pydantic>=2.0.0"]
adaptix = ["adaptix>=3.0.0b12"]
msgspec = ["msgspec>=0.18.0"]
Expand Down
15 changes: 15 additions & 0 deletions site/guides/errors.md
Original file line number Diff line number Diff line change
Expand Up @@ -112,12 +112,27 @@ The error types describe different stages:
| Failure | What to handle |
| --- | --- |
| Network failure or timeout | `NetworkError` or `RequestTimeoutError`; do not assume an HTTP response exists. |
| Request that cannot succeed as sent, for example an unsupported URL scheme | `NonRetryableError`; fix the request instead of retrying. |
| Any other failure inside the HTTP backend | Plain `UniHTTPError`. |
| Unsuccessful HTTP status | Exceptions configured by your mapper or error hooks. |
| API error inside a successful HTTP response | Your own exception from `validate_response`, as below. |
| Body does not match the declared result | The configured serializer's loading exception; this is not an HTTP status error. |

Avoid treating all of these as “user not found” or retrying every exception.

Every [client backend](../integrations/backends.md) translates failures of
sending a request and reading its response into these types, so you do not need
to catch backend exceptions for them. All inherit from `UniHTTPError`; the
original is kept as `__cause__`. Rare edge cases can map differently between
backends. Misuse is not translated: a request on a closed client raises the
backend's own error, for example `RuntimeError`.

Handle statuses with unihttp, not with the backend. If the backend session raises
on error statuses itself (for example `aiohttp.ClientSession(raise_for_status=True)`),
hooks and middleware never see the response, and you get a plain `UniHTTPError`.
Use an [error mapper](#map-statuses-across-endpoints) or override
`client.handle_error` to call `response.raise_for_status()` instead.

## Validate an error inside HTTP 200

Some APIs return `{"ok": false, "error": "Account disabled"}` with status `200`.
Expand Down
4 changes: 4 additions & 0 deletions site/guides/streaming.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,10 @@ For the helpers above, catch around the entire `download_checksum(...)` call
- `HTTPStatusError` covers rejected statuses, including the `ClientError` and
`ServerError` subclasses raised by this method.
- `NetworkError` and `RequestTimeoutError` can occur while opening or reading.
A body cut short by the server raises `NetworkError`; the stream does not
just end early.
- `NonRetryableError` means the request cannot succeed as sent, for example an
unsupported URL scheme.
- Exceptions from your own consumer also propagate; the stream context still
closes the response.

Expand Down
3 changes: 2 additions & 1 deletion site/recipes/retries.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,8 @@ The default is three retries, or four attempts total.
By default, status retries cover `500`, `502`, `503`, and `504`. Pass a non-empty
`status_codes` list to choose another set. Exceptions are not retried unless
included in `exceptions`; the example opts into `NetworkError` and
`RequestTimeoutError`.
`RequestTimeoutError`. Do not add `NonRetryableError`, which fails the same way
on every attempt, or the base `UniHTTPError`, which also covers it.

The delay before retry number `attempt + 1` is `backoff * 2**attempt`, starting
at `attempt = 0`. Here the base delays are 0.5 and 1 second. With `jitter=True`,
Expand Down
2 changes: 1 addition & 1 deletion site/reference/middleware.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ description: Middleware handlers, retry and status-mapping configuration, loggin

Sync `Handler` and async `AsyncHandler` are callable aliases exported by `unihttp.middlewares`. Match the middleware variant to the client. See [middleware ordering](../guides/middleware.md) and [retry behavior](../recipes/retries.md).

`HTTPStatusError` exposes `response` and `status_code`. Status errors require explicit handling; default response hooks do not raise automatically. Network exception normalization depends on the transport.
`HTTPStatusError` exposes `response` and `status_code`. Status errors require explicit handling; default response hooks do not raise automatically. Every client backend translates its own exceptions into `NetworkError`, `RequestTimeoutError`, `NonRetryableError`, or plain `UniHTTPError`, keeping the original as `__cause__`.

::: unihttp.middlewares.base.Middleware

Expand Down
49 changes: 32 additions & 17 deletions src/unihttp/clients/aiohttp.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,39 @@
from aiohttp import ClientResponse, ClientSession, FormData

from unihttp.clients.base import BaseAsyncClient
from unihttp.exceptions import NetworkError, RequestTimeoutError
from unihttp.clients.errors import ErrorMap, translate_errors
from unihttp.exceptions import (
NetworkError,
NonRetryableError,
RequestTimeoutError,
UniHTTPError,
)
from unihttp.http import UploadFile
from unihttp.http.request import HTTPRequest
from unihttp.http.response import HTTPResponse
from unihttp.http.stream import AsyncChunkStream
from unihttp.middlewares.base import AsyncMiddleware
from unihttp.serialize import RequestDumper, ResponseLoader

# Timeout first: ServerTimeoutError is also a ClientConnectionError.
_ERROR_MAP: ErrorMap = {
RequestTimeoutError: TimeoutError,
# Explicit: status and misuse errors must fall through to plain UniHTTPError.
NetworkError: (
aiohttp.ClientConnectionError,
aiohttp.ClientPayloadError,
aiohttp.ClientHttpProxyError,
),
# After NetworkError: a certificate error is also a ValueError.
# ValueError: aiohttp raises it bare for forbidden characters in headers.
NonRetryableError: (
ValueError,
aiohttp.NonHttpUrlClientError,
aiohttp.TooManyRedirects,
),
UniHTTPError: aiohttp.ClientError,
}


class _AiohttpChunkStream(AsyncChunkStream):
def __init__(self, response: ClientResponse, chunk_size: int) -> None:
Expand All @@ -23,12 +48,8 @@ def __init__(self, response: ClientResponse, chunk_size: int) -> None:
self._iter = response.content.iter_chunked(chunk_size)

async def _fetch_chunk(self) -> bytes:
try:
with translate_errors(_ERROR_MAP):
return await anext(self._iter)
except aiohttp.ClientConnectionError as e:
raise NetworkError(str(e)) from e
except TimeoutError as e:
raise RequestTimeoutError(str(e)) from e

async def _close_response(self) -> None:
self._response.close()
Expand Down Expand Up @@ -105,31 +126,25 @@ def _build_data(self, request: HTTPRequest) -> FormData | str | bytes | None:
async def _do_request(self, request: HTTPRequest) -> ClientResponse:
data = self._build_data(request)

try:
with translate_errors(_ERROR_MAP):
return await self._session.request(
method=request.method,
url=urljoin(self.base_url, request.url),
headers=request.header,
params=request.query,
data=data,
)
except aiohttp.ClientConnectionError as e:
raise NetworkError(str(e)) from e
except TimeoutError as e:
raise RequestTimeoutError(str(e)) from e

async def make_request(self, request: HTTPRequest) -> HTTPResponse:
response = await self._do_request(request)

response_data: Any = None
try:
content = await response.read()
except aiohttp.ClientConnectionError as e:
response.close()
raise NetworkError(str(e)) from e
except TimeoutError as e:
with translate_errors(_ERROR_MAP):
content = await response.read()
except UniHTTPError:
response.close()
raise RequestTimeoutError(str(e)) from e
raise
if content:
try:
response_data = self.json_loads(content)
Expand Down
18 changes: 18 additions & 0 deletions src/unihttp/clients/errors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
from collections.abc import Generator
from contextlib import contextmanager

from unihttp.exceptions import UniHTTPError

ErrorMap = dict[type[UniHTTPError], type[BaseException] | tuple[type[BaseException], ...]]


@contextmanager
def translate_errors(mapping: ErrorMap) -> Generator[None, None, None]:
"""Re-raise backend exceptions as unihttp ones; the first matching entry wins."""
try:
yield
except Exception as e:
for target, types in mapping.items():
if isinstance(e, types):
raise target(str(e)) from e
raise
49 changes: 28 additions & 21 deletions src/unihttp/clients/httpx.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,37 @@
from httpx import AsyncClient, Client, Response

from unihttp.clients.base import BaseAsyncClient, BaseSyncClient
from unihttp.exceptions import NetworkError, RequestTimeoutError
from unihttp.clients.errors import ErrorMap, translate_errors
from unihttp.exceptions import (
NetworkError,
NonRetryableError,
RequestTimeoutError,
UniHTTPError,
)
from unihttp.http import UploadFile
from unihttp.http.request import HTTPRequest
from unihttp.http.response import HTTPResponse
from unihttp.http.stream import AsyncChunkStream, ChunkStream
from unihttp.middlewares.base import AsyncMiddleware, Middleware
from unihttp.serialize import RequestDumper, ResponseLoader

# Timeout first: TimeoutException is also a RequestError.
_ERROR_MAP: ErrorMap = {
RequestTimeoutError: httpx.TimeoutException,
# ValueError: a base_url that urljoin rejects.
NonRetryableError: (
ValueError,
httpx.InvalidURL,
httpx.UnsupportedProtocol,
httpx.LocalProtocolError,
httpx.TooManyRedirects,
httpx.DecodingError,
),
NetworkError: httpx.RequestError,
# StreamError and CookieConflict are misuse errors outside HTTPError.
UniHTTPError: (httpx.HTTPError, httpx.StreamError, httpx.CookieConflict),
}


class _HTTPXChunkStream(ChunkStream):
def __init__(self, response: Response, chunk_size: int) -> None:
Expand All @@ -23,12 +46,8 @@ def __init__(self, response: Response, chunk_size: int) -> None:
self._iter = response.iter_bytes(chunk_size)

def _fetch_chunk(self) -> bytes:
try:
with translate_errors(_ERROR_MAP):
return next(self._iter)
except httpx.NetworkError as e:
raise NetworkError(str(e)) from e
except httpx.TimeoutException as e:
raise RequestTimeoutError(str(e)) from e

def _close_response(self) -> None:
self._response.close()
Expand All @@ -43,12 +62,8 @@ def __init__(self, response: Response, chunk_size: int) -> None:
self._iter = response.aiter_bytes(chunk_size)

async def _fetch_chunk(self) -> bytes:
try:
with translate_errors(_ERROR_MAP):
return await anext(self._iter)
except httpx.NetworkError as e:
raise NetworkError(str(e)) from e
except httpx.TimeoutException as e:
raise RequestTimeoutError(str(e)) from e

async def _close_response(self) -> None:
await self._response.aclose()
Expand Down Expand Up @@ -111,7 +126,7 @@ def _build_content(self, request: HTTPRequest) -> Any:
def _do_request(self, request: HTTPRequest, *, stream: bool) -> Response:
content = self._build_content(request)

try:
with translate_errors(_ERROR_MAP):
files = self._convert_files(request.file) if request.file else None
built_request = self._session.build_request(
method=request.method,
Expand All @@ -123,10 +138,6 @@ def _do_request(self, request: HTTPRequest, *, stream: bool) -> Response:
data=request.form,
)
return self._session.send(built_request, stream=stream)
except httpx.NetworkError as e:
raise NetworkError(str(e)) from e
except httpx.TimeoutException as e:
raise RequestTimeoutError(str(e)) from e

def make_request(self, request: HTTPRequest) -> HTTPResponse:
response = self._do_request(request, stream=False)
Expand Down Expand Up @@ -220,7 +231,7 @@ def _build_content(self, request: HTTPRequest) -> Any:
async def _do_request(self, request: HTTPRequest, *, stream: bool) -> Response:
content = self._build_content(request)

try:
with translate_errors(_ERROR_MAP):
files = self._convert_files(request.file) if request.file else None
built_request = self._session.build_request(
method=request.method,
Expand All @@ -232,10 +243,6 @@ async def _do_request(self, request: HTTPRequest, *, stream: bool) -> Response:
data=request.form,
)
return await self._session.send(built_request, stream=stream)
except httpx.NetworkError as e:
raise NetworkError(str(e)) from e
except httpx.TimeoutException as e:
raise RequestTimeoutError(str(e)) from e

async def make_request(self, request: HTTPRequest) -> HTTPResponse:
response = await self._do_request(request, stream=False)
Expand Down
Loading
Loading