Exception mapping
Every provider reports errors differently. The gateway maps them to a single set of exception types that subclass the OpenAI SDK exceptions, so code written against the OpenAI SDK can catch errors from any provider. The gateway returns the same mapping as HTTP status codes with an OpenAI shaped error body, and the router uses the type to decide whether to retry, cool down a deployment or fall back. The mapping is part of the free gateway and needs no configuration.
A real-world scenario
A support bot catches openai.RateLimitError and shows users a friendly "busy, try again" message. The team adds Anthropic and Bedrock deployments behind the same model name. Because the gateway maps both providers' rate limit responses to the same 429 status, with the type throttling_error and a message starting spanway.RateLimitError:, the bot's error handling keeps working without a change, the router retries the call on another deployment, and the Logs page groups all three providers' rate limits under one error code.
Step by step
In the Admin UI
- Open
/ui/logsas a proxy admin and filter on failed requests. Each row shows the mapped status code and the error type, with the original provider message in the details. - Open
/ui/caching, pick Cache Analytics and click a red Failed requests segment in the Cache Hits vs API Requests chart. The Failed requests by error code card shows one bar per mapped code, and hovering a bar lists the error classes behind it. - Open
/ui/router-settings, pick the Loadbalancing tab and set Number of Retries, Allowed Fails and Cooldown Time, which act on these mapped types. On the Fallbacks tab add a fallback chain for the models whose errors should move traffic elsewhere.
With curl
Send a request that fails and read the mapped error. The prompt is about 2 MB, too long for one command line, so write the body to a file first and let curl read it.
python3 -c 'import json; print(json.dumps({"model": "claude-haiku-5-5", "messages": [{"role": "user", "content": "a " * 1000000}]}))' > big.json
curl -i -X POST http://localhost:4000/v1/chat/completions \
-H "Authorization: Bearer $SPANWAY_API_KEY" \
-H "Content-Type: application/json" \
-d @big.json
Catch the same errors with the OpenAI SDK pointed at the gateway.
import os
from openai import BadRequestError, OpenAI, RateLimitError
client = OpenAI(base_url="http://localhost:4000", api_key=os.environ["SPANWAY_API_KEY"])
try:
client.chat.completions.create(model="claude-sonnet-5-5", messages=[{"role": "user", "content": "Hello"}])
except BadRequestError as e:
print("Refused:", e.message)
except RateLimitError as e:
print("Rate limited:", e.message)
Because the gateway answers with OpenAI status codes and error bodies, except openai.RateLimitError catches a rate limit from Anthropic, Bedrock or any other provider.
Expected result
The oversized request is refused with 400 and the body names the mapped type, the provider and the original message.
{
"error": {
"message": "spanway.ContextWindowExceededError: AnthropicException - prompt is too long",
"type": "invalid_request_error",
"param": null,
"code": "400"
}
}
A rate limit from any provider comes back as 429 with "type": "throttling_error" and a message that starts with spanway.RateLimitError:. A limit the gateway itself enforces, such as a key's rpm_limit, comes back as 429 with "type": "rate_limit_error", so the type tells you whether the provider or your own limits refused the call. The OpenAI SDK raises RateLimitError for both, because it chooses by status. Set general_settings.include_call_id_in_error_body: true to add error.spanway_call_id to error bodies, which matches the x-spanway-call-id response header and the spend log row so a support ticket can be traced to one request.
Exception types
The class name starts the error message. The type field holds the OpenAI style type listed for each class in the error reference.
| Exception | Status | Typical cause |
|---|---|---|
BadRequestError | 400 | Invalid parameters or payload. |
UnsupportedParamsError | 400 | A parameter the provider does not support, see drop params. |
ContextWindowExceededError | 400 | The prompt is longer than the model's context window. |
ContentPolicyViolationError | 400 | The provider's content filter refused the request. |
AuthenticationError | 401 | Invalid or missing provider credential. |
PermissionDeniedError | 403 | The credential may not use this model or resource. |
NotFoundError | 404 | Unknown model or deployment. |
PaymentRequiredError | 402 | The provider account is out of credit or needs a payment. |
UnprocessableEntityError | 422 | The provider could not process the request. |
Timeout | 408 | The provider did not answer within the request timeout. |
RateLimitError | 429 | The provider rate limited the call. |
InternalServerError | 500 | Provider side failure. |
BadGatewayError | 502 | Invalid response from the upstream provider. |
ServiceUnavailableError | 503 | Provider overloaded or unavailable. |
APIConnectionError | 500 | Network failure or timeout reaching the provider. |
APIError | varies | Any other provider error, with the original status code. |
RejectedRequestError | 400 | A gateway hook, such as a custom pre-call check, refused a chat or text completion before any provider was called. The hook's text is the message. |
APIResponseValidationError | 500 | The provider answered, but the answer did not have the shape the gateway expected. |
OpenAIError | varies | The base type every exception above shares. Catch it to handle any provider error at once. |
JSONSchemaValidationError | 500 | The answer did not match the requested JSON schema. With structured output repair on, the gateway answers 422 StructuredOutputRepairError once it gives up. |
GuardrailRaisedException, BlockedPiiEntityError | 400 | A guardrail refused the request or the answer. |
MidStreamFallbackError | 503 | A stream failed after it started and no fallback could finish it. |
ImageFetchError, VectorStoreSearchError, SpanwayUnknownProvider | 400 | An image URL could not be fetched, a vector store could not be searched, or the model names no supported provider. |
BudgetExceededError | 422 | A key, user, team or end user budget is exhausted. Set spanway_settings.budget_exceeded_status_code: 429 to return 429 instead. |
Every exception carries llm_provider and model attributes, and the original provider message is kept in the error text so nothing is lost in translation.
How the router uses the mapping
Retries per error type are configured with retry_policy (for example RateLimitErrorRetries or AuthenticationErrorRetries), cooldown thresholds with allowed_fails_policy, and dedicated fallback lists exist for ContextWindowExceededError and ContentPolicyViolationError. See routing.
Errors
| What you see | Why | Fix |
|---|---|---|
A 400 that should have been a 429 | The provider returned an unusual body the mapping treats as a bad request. | Read the original message in error.message and open a support request at support@spanway.ai with the provider and the body. |
APIError with the provider's own status code | The provider sent an error outside the known types. | Handle openai.APIError as the catch-all in your code. |
422 on a spent budget where your client expects 429 | The default budget status is 422. | Set spanway_settings.budget_exceeded_status_code: 429. |
No spanway_call_id in the error body | The setting is off by default. | Set general_settings.include_call_id_in_error_body: true, or read the x-spanway-call-id header. |
| The router does not retry an error you expect it to | retry_policy sets that type's retries to zero, or the type has no retries by default, such as authentication errors. | Set the type's entry in retry_policy. |
Related
- Routing explains retries, cooldowns and the fallback lists per error type.
- Reliability shows them working together.
- Logs page shows the mapped error of every failed request.
- Drop params avoids
UnsupportedParamsError.