Error Codes and What Each One Means
Why This Reference Matters Now
Every prior unit's code examples assumed a successful response — an occasional try/except appeared around a specific risky operation (Unit 6, Lesson 4's refusal handling; Unit 8, Lesson 5's tool-call error handling), but this course hasn't yet covered the full space of ways a request to the platform can fail before it ever reaches the model at all. Moving a project from a working prototype to something serving real users means handling every one of these failure modes deliberately, rather than letting an unhandled exception crash the application or silently return a confusing result. This lesson catalogs what actually goes wrong and why; Lessons 2 and 3 build the retry and rate-limiting logic that responds to it.
The Error Response Shape
When a request fails, the SDK raises an exception carrying the HTTP status code and an error object describing what went wrong.
from openai import OpenAI, APIError, APIStatusError
client = OpenAI()
try:
response = client.responses.create(
model="gpt-5.6-terra",
input="Hello",
)
except APIStatusError as e:
print(f"Status code: {e.status_code}")
print(f"Error message: {e.message}")
Note: The exact exception class names and the attributes available on them can vary by SDK version. Confirm the current exception hierarchy against your installed SDK version's documentation before relying on a specific attribute name in production code.
Catching a specific exception type, as shown here, rather than a bare except Exception, is what makes it possible to handle different failure categories differently — a request that failed because of a temporary server issue calls for a different response than one that failed because the request itself was malformed, and the exception type (or the status code it carries) is how that distinction gets made in code.
The Common Status Codes and What They Mean
| Status Code | Meaning | Typical Cause | Appropriate Response |
|---|---|---|---|
| 400 | Bad Request | Malformed request — invalid parameter, invalid JSON Schema (Unit 6) | Fix the request; retrying without changing anything won't help |
| 401 | Unauthorized | Missing or invalid API key | Check that OPENAI_API_KEY (Unit 1, Lesson 3) is set and valid; retrying won't help |
| 403 | Forbidden | The API key doesn't have access to the requested resource or model | Check account permissions and model access; retrying won't help |
| 404 | Not Found | Referencing a resource that doesn't exist (an invalid vector store ID, Unit 9, Lesson 2; a stale previous_response_id, Unit 4, Lesson 3) | Verify the referenced ID is correct and still exists; retrying won't help unless the resource is recreated |
| 429 | Too Many Requests | Rate limit exceeded (Lesson 3) or a spending limit reached | Back off and retry after a delay (Lesson 2); a spend-limit case needs a raised limit, not a retry |
| 500 | Internal Server Error | A problem on the platform's side, unrelated to your request | Retry with backoff (Lesson 2) — the request itself is likely fine |
| 503 | Service Unavailable | The service is temporarily overloaded or down for maintenance | Retry with backoff (Lesson 2) |
The single most important distinction in this table is between an error caused by something wrong with your request (400, 401, 403, 404 — collectively, client errors) and an error caused by something on the platform's side or by legitimate throttling (429, 500, 503 — collectively, retryable errors). Retrying a 400 error without changing anything about the request will simply produce the same 400 error again; retrying a 500 or 503 error after a short delay often succeeds, since the underlying condition causing it is frequently transient.
Distinguishing Client Errors From Retryable Errors in Code
def is_retryable(status_code: int) -> bool:
"""Illustrative — confirm the current set of retryable status codes
against your installed SDK version's documentation, since guidance
on which specific codes warrant a retry can be refined over time."""
return status_code in (429, 500, 503)
def is_client_error(status_code: int) -> bool:
return status_code in (400, 401, 403, 404)
This distinction is the foundation Lesson 2's retry logic builds on directly: a retry loop that doesn't check this distinction first and simply retries every failure indiscriminately wastes time and cost repeating a 400 error that will never succeed, while correctly retrying the 429s and 500s that might.
Reading the Error Body for More Detail
Beyond the status code, the error response body typically includes a more specific error type and message describing exactly what was wrong with the request — valuable for debugging a 400 error in particular, since "Bad Request" alone doesn't say which part of the request was malformed.
try:
response = client.responses.create(
model="gpt-5.6-terra",
input="Hello",
temperature=5.0, # deliberately invalid — out of the valid range
)
except APIStatusError as e:
print(f"Status: {e.status_code}")
print(f"Error type: {getattr(e, 'type', 'unknown')}")
print(f"Detail: {e.message}")
Note: The exact fields available on an error's body (an error
type, aparamidentifying which specific parameter was invalid, and similar) can vary by SDK version. Confirm the current error body shape against your installed SDK version's documentation.
Logging this level of detail during development — not just "the request failed" but specifically what was wrong with it — is what turns a confusing 400 error into an actionable one, especially for an error caused by a parameter deep in a complex request (a malformed JSON Schema in a structured output, Unit 6, Lesson 2; an invalid tool definition, Unit 8, Lesson 2).
Errors That Aren't HTTP Status Codes at All
Not every failure mode originates from the platform's response. A request can also fail before it's ever sent — a network timeout, a connection error, a client-side validation failure (an SDK catching a malformed argument before making the request at all) — and these are typically represented as distinct exception types rather than sharing the same status-code-based hierarchy as a server response.
from openai import APIConnectionError, APITimeoutError
try:
response = client.responses.create(model="gpt-5.6-terra", input="Hello")
except APITimeoutError:
print("The request timed out before receiving a response.")
except APIConnectionError:
print("A network-level connection error occurred.")
except APIStatusError as e:
print(f"The platform returned an error: {e.status_code}")
Distinguishing a connection-level failure from a platform-returned error matters because the appropriate response can differ: a connection error might indicate a local network issue worth surfacing differently to a user than a clear "the service is temporarily overloaded" message a 503 status code provides.
Common Mistakes
Catching a bare Exception and treating every failure identically, rather than distinguishing client errors (which retrying won't fix) from retryable errors (which often succeed on retry).
Retrying a 400 or 401 error without changing anything about the request, wasting time and cost on a request that will fail identically every time until the actual problem — an invalid parameter, a bad API key — is fixed.
Ignoring the detailed error message and type in favor of just the status code, missing specific information (which parameter was invalid, what exactly was wrong) that would make debugging a malformed request considerably faster.
Failing to distinguish a network-level connection error from a platform-returned error, when the two suggest different underlying causes and potentially different responses.
Best Practices
Catch specific exception types rather than a bare Exception, so client errors, retryable errors, and connection-level failures can each be handled appropriately.
Log the full error detail — status code, error type, and message — during development, not just the fact that a request failed, to make debugging a malformed request faster.
Build a clear mental model of which status codes are retryable and which aren't before writing any retry logic, since Lesson 2's backoff strategy depends entirely on getting this distinction right.
Treat a 429 rate-limit error and a spend-limit error as needing different responses, even though both can surface as the same status code — one needs a delay and retry, the other needs an actual change to account limits, a distinction Lesson 3 covers in depth.