Skip to main content

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​

  1. Open /ui/logs as 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.
  2. 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.
  3. 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.

ExceptionStatusTypical cause
BadRequestError400Invalid parameters or payload.
UnsupportedParamsError400A parameter the provider does not support, see drop params.
ContextWindowExceededError400The prompt is longer than the model's context window.
ContentPolicyViolationError400The provider's content filter refused the request.
AuthenticationError401Invalid or missing provider credential.
PermissionDeniedError403The credential may not use this model or resource.
NotFoundError404Unknown model or deployment.
PaymentRequiredError402The provider account is out of credit or needs a payment.
UnprocessableEntityError422The provider could not process the request.
Timeout408The provider did not answer within the request timeout.
RateLimitError429The provider rate limited the call.
InternalServerError500Provider side failure.
BadGatewayError502Invalid response from the upstream provider.
ServiceUnavailableError503Provider overloaded or unavailable.
APIConnectionError500Network failure or timeout reaching the provider.
APIErrorvariesAny other provider error, with the original status code.
RejectedRequestError400A 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.
APIResponseValidationError500The provider answered, but the answer did not have the shape the gateway expected.
OpenAIErrorvariesThe base type every exception above shares. Catch it to handle any provider error at once.
JSONSchemaValidationError500The answer did not match the requested JSON schema. With structured output repair on, the gateway answers 422 StructuredOutputRepairError once it gives up.
GuardrailRaisedException, BlockedPiiEntityError400A guardrail refused the request or the answer.
MidStreamFallbackError503A stream failed after it started and no fallback could finish it.
ImageFetchError, VectorStoreSearchError, SpanwayUnknownProvider400An image URL could not be fetched, a vector store could not be searched, or the model names no supported provider.
BudgetExceededError422A 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 seeWhyFix
A 400 that should have been a 429The 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 codeThe 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 429The default budget status is 422.Set spanway_settings.budget_exceeded_status_code: 429.
No spanway_call_id in the error bodyThe 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 toretry_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.
  • 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.