错误处理
2026/7/28大约 1 分钟
错误处理
当 API 请求出错时,服务器会返回标准的 JSON 格式错误响应。
错误响应格式
{
"error": {
"message": "错误描述信息",
"type": "错误类型",
"param": null,
"code": "错误代码"
}
}HTTP 状态码
| 状态码 | 含义 | 说明 |
|---|---|---|
| 200 | 成功 | 请求成功 |
| 400 | 请求错误 | 请求参数有误 |
| 401 | 未授权 | API Key 无效或缺失 |
| 403 | 禁止访问 | 没有权限访问该资源 |
| 404 | 未找到 | 请求的资源不存在 |
| 429 | 请求过多 | 超出速率限制 |
| 500 | 服务器错误 | 服务器内部错误 |
| 502 | 网关错误 | 上游服务不可用 |
| 503 | 服务不可用 | 服务暂时不可用 |
常见错误码
| 错误码 | 类型 | 说明 | 解决方案 |
|---|---|---|---|
invalid_request_error | 400 | 请求参数无效 | 检查请求参数格式 |
authentication_error | 401 | 认证失败 | 检查 API Key 是否正确 |
insufficient_quota | 402 | 配额不足 | 充值或升级套餐 |
model_not_found | 404 | 模型不存在 | 检查模型名称是否正确 |
rate_limit_error | 429 | 速率限制 | 降低请求频率 |
server_error | 500 | 服务器错误 | 稍后重试或联系客服 |
错误处理建议
重试策略
对于临时性错误(429、500、502、503),建议实现指数退避重试:
import time
import openai
def call_with_retry(client, max_retries=3):
for i in range(max_retries):
try:
return client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "Hello"}]
)
except openai.RateLimitError:
time.sleep(2 ** i) # 指数退避
except openai.APIError as e:
if e.code >= 500 and i < max_retries - 1:
time.sleep(2 ** i)
else:
raise
raise Exception("Max retries exceeded")错误日志
建议记录所有错误响应,以便排查问题:
import logging
try:
response = client.chat.completions.create(...)
except Exception as e:
logging.error(f"API Error: {e}")
# 处理错误
