Error Codes and What Each One Means

Ma Mahalakshmi V Updated 16 Sep 2026
6 min read ·Lesson 54 of 224

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 CodeMeaningTypical CauseAppropriate Response
400Bad RequestMalformed request — invalid parameter, invalid JSON Schema (Unit 6)Fix the request; retrying without changing anything won't help
401UnauthorizedMissing or invalid API keyCheck that OPENAI_API_KEY (Unit 1, Lesson 3) is set and valid; retrying won't help
403ForbiddenThe API key doesn't have access to the requested resource or modelCheck account permissions and model access; retrying won't help
404Not FoundReferencing 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
429Too Many RequestsRate limit exceeded (Lesson 3) or a spending limit reachedBack off and retry after a delay (Lesson 2); a spend-limit case needs a raised limit, not a retry
500Internal Server ErrorA problem on the platform's side, unrelated to your requestRetry with backoff (Lesson 2) — the request itself is likely fine
503Service UnavailableThe service is temporarily overloaded or down for maintenanceRetry 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, a param identifying 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.

0 Comments

Reviewed before they appear

No comments yet.

OpenAI SDK
Introduction to the OpenAI SDK Setting Up Python Creating an API Key Your First Call — client.responses.create() and response.output_text Understanding Billing, Credits, and What a Request Costs Why Responses Replaced Chat Completions Anatomy of a Request: model, input, and instructions Anatomy of a Response: The Typed output Array, Not Just Text Roles: User, Assistant, and Developer/System Choosing a Model, and Reading the Models Page Instead of Memorizing Names Instructions vs. Input Writing Prompts That Get Consistent Results Few-Shot Examples Reasoning Models and the reasoning Parameter Debugging a Prompt That Misbehaves Why Streaming Matters for User Experience stream=True and Iterating Over Events Handling the Event Types You Actually Care About Background Mode for Long-Running Jobs Project — Add Live Streaming to Your Chatbot The Problem With Parsing Free Text JSON Schema and Strict Mode Pydantic Models With the SDK's Parse Helpers Handling Refusals and Validation Failures Project — A Resume-to-JSON Extractor Working With input_image input_file, PDFs, and the Files API Image Generation Speech-to-Text and Text-to-Speech Project: A PDF Question-Answering Script What Function Calling Is Defining a Tool Schema The Full Loop Multiple Tools Errors, Timeouts, and Untrusted Arguments Project: A Weather Assistant Web Search File Search and Vector Stores Code Interpreter Remote MCP Servers and Connectors Project: A Research Assistant What an Embedding Is, Without the Maths Generating and Storing Embeddings Similarity Search From Scratch Hosted Vector Stores vs. Rolling Your Own A Small RAG App Over a Folder of Notes Agents vs. a Single API Call — When You Need One pip install openai Giving Agents Tools Handoffs and Multi-Agent Triage Guardrails and Approvals Tracing and Observing What Your Agent Did A Multi-Agent Support Desk Error Codes and What Each One Means Retries, Timeouts, and Backoff Rate Limits and Spend Limits Prompt Caching and Cost Optimisation The Batch API for Bulk Work Async Clients and Concurrency Moderation and Safety Best Practices Designing the App Backend With FastAPI Streaming to a Simple Frontend Deploying and a Cost/Safety Checklist Why Web Search Is Useful for Current Information Using the Web Search Tool with the Responses API Configuring Search Behavior for Application Use Cases Understanding Citations and Source Attribution Where to Go Next Building a Research Assistant with Web Search Combining Web Search with Structured Outputs Handling Conflicting or Low-Quality Web Sources Reducing Unsupported Claims with Grounded Generation Testing Freshness-Sensitive AI Answers Production Considerations for Web-Grounded Applications Understanding File Search and Retrieval-Augmented Generation Creating and Organizing Vector Stores Uploading Documents for Retrieval Connecting Vector Stores to Responses API Requests Designing Document Metadata and Filtering Strategies Building a PDF Question-Answering Application Improving Retrieval Quality With Better Document Preparation Handling Missing Evidence and Retrieval Failures Combining File Search With Web Search Building a Production Knowledge-Base Assistant What the Code Interpreter Tool Is Designed For Running Python-Based Analysis Through the OpenAI SDK Uploading Datasets for Analysis Analyzing CSV and Spreadsheet Data Generating Charts and Data Summaries Handling Generated Files and Downloadable Artifacts Building a Data-Analysis Assistant Combining Code Execution with Structured Outputs Validating Generated Calculations and Results Security and Sandbox Considerations for Code Execution Understanding Multimodal Input with the OpenAI SDK Sending Images to a Model Image Analysis from URLs and Uploaded Files Extracting Text and Information from Screenshots Building an Image-Question-Answering Application Combining Image Input with Structured Output Analyzing Multiple Images in One Request Handling Image Quality and Input Limitations Designing Multimodal Prompts for Reliable Results Building a Practical Vision-Powered Python Application Understanding Speech-to-Text and Text-to-Speech Workflows Transcribing Audio with the OpenAI SDK Working with Uploaded Audio Files Handling Timestamps and Transcription Metadata Building a Meeting Transcription Workflow Generating Spoken Responses from Text Handling Long Audio and Processing Failures Combining Audio with Text and Tool Calling Building an End-to-End Python Voice Application What Embeddings Are and When to Use Them Generating Embeddings With the OpenAI API Preparing Text for Embedding Comparing Vectors With Cosine Similarity Building a Simple Semantic Search Engine in Python Storing Embeddings in a Database Metadata Filtering for Semantic Search Chunking Strategies for Better Retrieval Evaluating Semantic Search Quality Building a Document Similarity Application When Batch Processing Makes Sense Designing Large-Volume AI Processing Pipelines Using Asynchronous Python with the OpenAI SDK Running Concurrent Requests Safely Controlling Concurrency and Avoiding Rate Limits Tracking Batch Job Progress Handling Partial Failures in Bulk Workloads Retrying Failed Items Without Duplicating Successful Work Designing Resumable AI Processing Jobs Building a Production Batch-Processing Pipeline Batch Processing Makes Sense Large-Scale AI Processing Pipelines Async Python with OpenAI SDK Safe Concurrent Requests Concurrency & Rate Limits Batch Progress Tracking Partial Failure Handling Safe Retry Handling Resumable AI Jobs Production Batch Pipeline System–User Data Separation Reusable App Instructions Prompt Templates & Variables Extraction & Classification Prompts Summarization & Transformation Prompts Explicit Output Requirements Prompt Version Management Prompt Testing & Evaluation Reusable Python Prompt Library API Key Security Secure API Key Storage Secure Secret Management Prompt Injection Prevention Trusted vs. Untrusted Content Tool Argument Validation Sensitive Data Handling Secure Logging AI Action Authorization Production AI Security Checklist Why AI Applications Need Evaluation Beyond Unit Tests Unit Testing OpenAI SDK Integration Code Mocking API Responses in Python Tests Testing Structured Outputs Against Schemas Testing Tool-Calling Workflows Building a Small Evaluation Dataset Measuring Accuracy, Consistency, and Failure Rates Regression Testing Prompts and Model Changes Human Evaluation Versus Automated Evaluation Creating a Repeatable Evaluation Pipeline AI Request Monitoring Token Cost Management Usage Metrics Design Reducing Model Calls Prompt & Context Optimization Model Selection & Optimization AI Caching Strategies Interactive Latency Optimization Usage Dashboards & Budget Alerts Performance & Cost Checklist Every API Call Starts Fresh Fixing API Statelessness Server-Side Conversation Memory Limits of Response Chaining What We're Building Conversation Memory Challenges Preparing an OpenAI SDK Application for Deployment Environment-Specific Configuration for Development and Production Deploying a Python AI Service with Docker Container Health Checks and Startup Configuration Managing Secrets in Cloud Deployments Background Workers for Long-Running AI Tasks Queues and Asynchronous Job Architectures Scaling AI Workloads Horizontally Monitoring Production Incidents and Failures Production Deployment Checklist for OpenAI SDK Applications Reusable OpenAI Service Classes AI Client Dependency Injection Typed AI Responses Python Configuration Management AI Request Decorators Centralized AI Error Handling Clean SDK Abstractions Reusable OpenAI Utilities Internal AI Python Libraries SDK Integration Maintenance Production AI Chatbot Document Q&A System Web Research Assistant Customer Support Agent AI Data Analysis Assistant Image Analysis App Meeting Transcription & Summary Semantic Document Search Multi-Tool AI Agent Production OpenAI SDK App Why "It Looked Fine When I Tested It" Isn't Enough Timing Note Status Note Pre-Decision Status Note Current Availability Note
Ask about this post
AI Ask about this post

Ask questions about Error Codes and What Each One Means and get answers drawn from it.

Signed-in readers only.