Sub topic 8
Normalizing errors
This chapter assumes you have the neutral types, the ChatProvider protocol, and at least one adapter from earlier chapters. You should also know common HTTP status codes.
Why errors need a neutral form
Each provider reports failures differently. One returns HTTP 429 with a JSON error.type field. Another uses a different field name or a different status for "overloaded". SDKs add their own exception classes on top. If these leak out of the adapters, every caller needs except openai.RateLimitError and except anthropic.RateLimitError. That brings back the coupling the interface was meant to remove.
The fix is the same as for requests and responses. Each adapter catches provider-specific failures and raises one error type. Callers and the fallback logic only see that type.
What the neutral error carries
Callers usually need to decide only one thing: would trying again, here or elsewhere, help? So the error carries a retryable flag. A short kind and the HTTP status help with logging and metrics.
class ProviderError(Exception):
def __init__(
self,
message: str,
retryable: bool,
kind: str = "unknown",
status: int | None = None,
):
super().__init__(message)
self.retryable = retryable
self.kind = kind
self.status = statusThe extra fields have defaults, so code that builds ProviderError(message, retryable) still works.
Mapping statuses to categories
Most providers follow HTTP conventions closely enough to share one classifier. Put it in a common module and let each adapter call it. Add provider-specific cases in the adapter only when a body or header requires it.
| Situation | Typical status | `kind` | `retryable` |
|---|---|---|---|
| Rate limit or quota burst | 429 | `rate_limit` | yes |
| Provider overloaded or failing | 500, 502, 503, 529 | `server` | yes |
| Timeout or connection failure | none | `network` | yes |
| Bad API key or permissions | 401, 403 | `auth` | no |
| Malformed request, too many tokens | 400, 404, 413, 422 | `invalid_request` | no |
import httpx
def from_http_status(status: int, message: str) -> ProviderError:
if status == 429:
return ProviderError(message, True, "rate_limit", status)
if status >= 500:
return ProviderError(message, True, "server", status)
if status in (401, 403):
return ProviderError(message, False, "auth", status)
if status in (400, 404, 413, 422):
return ProviderError(message, False, "invalid_request", status)
return ProviderError(message, False, "unknown", status)
def send_normalized(send) -> httpx.Response:
try:
response = send()
except (httpx.TimeoutException, httpx.TransportError) as exc:
raise ProviderError(str(exc), True, "network") from exc
if response.status_code >= 400:
raise from_http_status(response.status_code, response.text)
return response
try:
send_normalized(lambda: httpx.Response(503, text="busy"))
except ProviderError as err:
assert err.retryable and err.kind == "server" and err.status == 503This example needs the httpx package. An adapter wraps its real HTTP call in send_normalized. If it uses a vendor SDK instead, it catches the SDK's exception classes and calls from_http_status with the status attribute they expose.
Common mistakes
- Marking everything retryable. An invalid request fails the same way on every provider. Retrying wastes time and money, and it hides the bug.
- Swallowing the original exception. Use
raise ... from excso the vendor traceback stays available in logs. - Putting secrets in messages. Error bodies can echo request details. Keep API keys out of messages and logs.
- Treating auth as a fallback case. A 401 usually means your own configuration is wrong. The fallback chain should surface it, not skip past it.
- Ignoring provider-specific meanings. Some providers return 400 for a context-length overflow. It stays non-retryable here, since the same request fails again. Switching to a larger-context model is a separate decision for the caller.
The retryable flag is what complete_with_fallback reads in a later chapter. It moves to the next provider only when the flag is true and re-raises everything else.
Exercise
A provider returns HTTP 408 (request timeout) from a gateway in front of its API. Which category would you map it to, and why? What would you change in from_http_status?
Show answer
Treat it as retryable, since a timeout is transient and another attempt or provider may succeed. Add a branch such as if status in (408, 429): return ProviderError(message, True, "rate_limit" if status == 429 else "network", status). Without it, 408 falls into the final case and is marked non-retryable, which would stop fallback on a transient failure.