Sub topic 8
Normalizing errors
This chapter assumes you have read the earlier chapters of this tutorial. You should know the neutral ChatRequest and ChatResponse types, the ChatProvider protocol, and how an adapter wraps one provider's HTTP API. You should also know the common HTTP status codes and how Python exceptions propagate.
Why errors need their own abstraction
Neutral request and response types hide the shape of a successful call. Failures leak through if you don't handle them. An OpenAI SDK raises openai.RateLimitError. An Anthropic SDK raises anthropic.RateLimitError. A plain HTTP client raises nothing and returns a status code. If calling code catches these classes directly, it imports every provider SDK. The coupling you removed from the success path comes back through except clauses.
Error handling is also where a switchable design pays off most. Retry and fallback logic needs one question answered the same way for every provider: is it worth trying again, or somewhere else? The adapter's job is to answer that question once, at the boundary, so no other code has to know provider-specific details.
The goal has three parts:
- Callers catch one exception type,
ProviderError. - That exception carries a small, fixed vocabulary of error kinds.
- The original provider detail is kept for logs and debugging, not for control flow.
What providers actually report
The same underlying problem looks different on each provider.
| Situation | Typical HTTP status | Provider-specific signal |
|---|---|---|
| Too many requests per minute | 429 | Often a `Retry-After` header |
| Account out of credit or quota | 429 on some providers, 402 or 403 on others | OpenAI uses the error type `insufficient_quota` |
| Server overloaded | 503, or 529 on Anthropic | Error type such as `overloaded_error` |
| Bad API key | 401 | Body text varies |
| Malformed request | 400 | Body names the bad field |
| Prompt too long | 400 or 413 | Error code or message text, which differs by provider |
| Request timed out | 408, 504, or no response | A client-side exception, not a status |
Two rows deserve attention. First, a status code alone is not enough: OpenAI returns 429 for both a temporary rate limit and an exhausted quota. Retrying the first is correct and retrying the second wastes time. Second, some failures never produce a status code. A timeout or a dropped connection raises an exception in your HTTP client, and your adapter has to translate that too.
Treat the table as a starting point. Status codes and error bodies change, so check each provider's current error reference when you write an adapter.
Designing the error type
Start with a closed set of kinds. Each kind should correspond to a different decision by the caller. If two kinds would always be handled identically, merge them.
from enum import Enum
class ErrorKind(Enum):
RATE_LIMIT = "rate_limit"
OVERLOADED = "overloaded"
TIMEOUT = "timeout"
NETWORK = "network"
QUOTA = "quota"
AUTH = "auth"
INVALID_REQUEST = "invalid_request"
CONTEXT_LENGTH = "context_length"
UNKNOWN = "unknown"
RETRYABLE_KINDS = {
ErrorKind.RATE_LIMIT,
ErrorKind.OVERLOADED,
ErrorKind.TIMEOUT,
ErrorKind.NETWORK,
}
class ProviderError(Exception):
def __init__(
self,
message: str,
kind: ErrorKind,
*,
provider: str,
status: int | None = None,
retry_after: float | None = None,
):
super().__init__(message)
self.kind = kind
self.provider = provider
self.status = status
self.retry_after = retry_after
@property
def retryable(self) -> bool:
return self.kind in RETRYABLE_KINDSretryable is derived from kind, not stored separately. That keeps the two from disagreeing, and the fallback function from the earlier example keeps working because it only reads err.retryable.
The exception keeps provider, status and retry_after as plain attributes. They are for logging and for backoff logic. Callers should branch on kind and retryable, not on status, because a status code means different things on different providers.
Translating HTTP errors
Each adapter converts its raw failure into a ProviderError. Much of the work is the same across providers, so a shared helper handles the common cases and each adapter adds its own exceptions.
def classify_status(status: int) -> ErrorKind:
if status == 429:
return ErrorKind.RATE_LIMIT
if status in (401, 403):
return ErrorKind.AUTH
if status in (408, 504):
return ErrorKind.TIMEOUT
if status in (500, 502, 503, 529):
return ErrorKind.OVERLOADED
if status == 413:
return ErrorKind.CONTEXT_LENGTH
if 400 <= status < 500:
return ErrorKind.INVALID_REQUEST
return ErrorKind.UNKNOWN
def parse_retry_after(headers: dict[str, str]) -> float | None:
value = headers.get("retry-after")
if value is None:
return None
try:
return max(0.0, float(value))
except ValueError:
return None # the header may also hold an HTTP date; ignore it
def _is_context_overflow(code: str, message: str) -> bool:
text = message.lower()
return (
code == "context_length_exceeded"
or "prompt is too long" in text
or "maximum context length" in text
)
def translate_http_error(
provider: str, status: int, headers: dict[str, str], body: object
) -> ProviderError:
headers = {k.lower(): v for k, v in headers.items()}
error = body.get("error") if isinstance(body, dict) else None
if not isinstance(error, dict):
error = {}
code = str(error.get("code") or error.get("type") or "")
message = str(error.get("message") or f"HTTP {status}")
kind = classify_status(status)
if code == "insufficient_quota":
kind = ErrorKind.QUOTA
elif status in (400, 413) and _is_context_overflow(code, message):
kind = ErrorKind.CONTEXT_LENGTH
return ProviderError(
message,
kind,
provider=provider,
status=status,
retry_after=parse_retry_after(headers),
)The body check runs after the status check, so the more specific signal wins. A 429 with insufficient_quota becomes QUOTA, which is not retryable. A 400 whose message says the prompt is too long becomes CONTEXT_LENGTH. Matching on message text is fragile, so keep those strings in one function where they are easy to update.
Run a few checks to confirm the translation behaves as intended:
err = translate_http_error(
"openai", 429, {"Retry-After": "2"},
{"error": {"type": "rate_limit_exceeded", "message": "slow down"}},
)
assert err.kind is ErrorKind.RATE_LIMIT and err.retryable
assert err.retry_after == 2.0
err = translate_http_error(
"openai", 429, {},
{"error": {"type": "insufficient_quota", "message": "out of credit"}},
)
assert err.kind is ErrorKind.QUOTA and not err.retryable
err = translate_http_error(
"anthropic", 529, {},
{"type": "error", "error": {"type": "overloaded_error", "message": "Overloaded"}},
)
assert err.kind is ErrorKind.OVERLOADED and err.retryable
err = translate_http_error(
"anthropic", 400, {},
{"error": {"type": "invalid_request_error",
"message": "prompt is too long: 250000 tokens > 200000 maximum"}},
)
assert err.kind is ErrorKind.CONTEXT_LENGTH and not err.retryableTranslating client exceptions
Timeouts and connection failures never reach translate_http_error, because there is no response. Wrap the network call in each adapter and convert those exceptions as well.
def call_normalized(provider: str, send):
"""Run send() and convert client-side failures into ProviderError."""
try:
return send()
except ProviderError:
raise
except TimeoutError as exc:
raise ProviderError(
"request timed out", ErrorKind.TIMEOUT, provider=provider
) from exc
except ConnectionError as exc:
raise ProviderError(
"connection failed", ErrorKind.NETWORK, provider=provider
) from excThree details matter here:
raise ... from exckeeps the original exception as__cause__, so tracebacks still show what the SDK reported.- The
exceptclauses cover only the network call. Do not wrap your own response parsing. If aKeyErrorin the adapter becomes a retryableProviderError, a real bug looks like a transient outage and gets retried until it burns your budget. - The messages are fixed text or taken from the error body. Never put request headers in a message, because they contain the API key.
Which kinds should trigger what
Normalization only helps if each kind maps to a clear policy. A reasonable default:
| Kind | Retry same provider | Fall back to another provider |
|---|---|---|
| `RATE_LIMIT` | Yes, after `retry_after` if present | Yes |
| `OVERLOADED` | Yes, with backoff | Yes |
| `TIMEOUT`, `NETWORK` | Yes, a limited number of times | Yes |
| `QUOTA` | No | Usually no, but alert someone |
| `AUTH` | No | No by default |
| `INVALID_REQUEST` | No | No |
| `CONTEXT_LENGTH` | No | Only if you deliberately route to a larger-context model |
| `UNKNOWN` | No | No |
INVALID_REQUEST is the clearest case for not falling back. A request that one provider rejects as malformed will usually be rejected by the next one, and you would double your latency to get the same error. The fallback function from the earlier example encodes this by re-raising anything not marked retryable.
AUTH is a judgment call. A bad key on provider A does not mean provider B is unusable, so falling back may keep the application working. It also hides a configuration mistake that someone should fix. If you do fall back on AUTH, log it loudly.
You can verify the fallback rule against the normalized errors with stand-in providers:
def complete_with_fallback(providers, request):
last_error = None
for provider in providers:
try:
return provider.complete(request)
except ProviderError as err:
if not err.retryable:
raise
last_error = err
raise last_error or ValueError("no providers configured")
class Failing:
def __init__(self, error):
self.error = error
def complete(self, request):
raise self.error
class Working:
def complete(self, request):
return "from backup"
busy = ProviderError("busy", ErrorKind.OVERLOADED, provider="a", status=529)
bad = ProviderError("bad field", ErrorKind.INVALID_REQUEST, provider="a", status=400)
assert complete_with_fallback([Failing(busy), Working()], None) == "from backup"
try:
complete_with_fallback([Failing(bad), Working()], None)
except ProviderError as err:
assert err.kind is ErrorKind.INVALID_REQUEST
else:
raise AssertionError("expected the invalid request to be re-raised")Edge cases and gotchas
- Unknown errors default to not retryable. If an adapter sees a status or error type it does not recognize, mapping it to
UNKNOWNis safer than guessing. Retrying an unknown failure can repeat a side effect or burn quota. Log the raw body so you can add a mapping later. - Errors can arrive inside a 200 response. Streaming responses start with a success status and may report a failure partway through. The streaming adapter has to raise
ProviderErrorfor those events as well. Once part of a response has been shown to a user, retrying silently is unsafe, because the new response may differ. - Rate-limit scope differs. Providers limit by requests per minute, tokens per minute, or both, sometimes per model. A
RATE_LIMITon one model does not mean the whole provider is unavailable. Keepproviderand the model in your logs. - Content refusals are not errors. A model declining a request normally comes back as a successful response with refusal text or a finish reason. Some providers also return a 400 for policy violations. Decide per kind whether you map that to
INVALID_REQUESTor add a dedicated kind. Don't retry it either way. - Keep the raw error reachable. The
__cause__link and thestatusattribute are enough for debugging. Do not copy the full response body into the exception message if it may echo user prompts into your logs.
Testing error handling
Normalization is easy to test because it is pure data translation. Feed recorded error bodies from each provider into translate_http_error and assert on kind. When a provider introduces a new error format, save a sample of it as a new test case. For code that reacts to errors, use fake providers that raise a chosen ProviderError, as in the fallback check above. You do not need network access to cover the rate-limit, overload and invalid-request paths.
Exercise
An adapter receives HTTP 429 from a provider, and the response body has the error type insufficient_quota. Which ErrorKind should it produce, and should fallback code move to the next provider because of it?
Show answer
It should produce QUOTA. A 429 usually means a temporary rate limit, but insufficient_quota means the account is out of credit, so waiting and retrying will not help. QUOTA is not in RETRYABLE_KINDS, so retryable is false and complete_with_fallback re-raises it. The error should be surfaced and alerted on rather than silently routed around.
Exercise
Why should an adapter wrap only the network call in the try block that converts exceptions to ProviderError, and not the code that parses the response?
Show answer
A bug in the parsing code, such as a KeyError from an unexpected response shape, would otherwise be converted into a retryable ProviderError. The caller would treat a permanent bug as a transient outage and retry or fall back repeatedly. Letting parsing errors propagate as ordinary exceptions makes the bug visible.