错误处理 — HTTP 状态码与重试策略
Claude API 常见错误码(401/402/429/500)含义及处理建议,附 Python 重试示例。
常见状态码
- 400 — 请求格式错误,检查 JSON 与字段名。
- 401 — API Key 无效或过期。
- 402 — 积分不足,请充值。
- 429 — 超出速率限制,请重试或提升限额。
- 500/502/503 — 上游 Anthropic 暂时不可用,建议重试。
Python 重试示例
import time
from anthropic import Anthropic, APIError
client = Anthropic(api_key="sk-cs2-...", base_url="https://api3.claudestore.store")
def call_with_retry(messages, max_retries=3):
for i in range(max_retries):
try:
return client.messages.create(
model="claude-sonnet-4.6",
max_tokens=1024,
messages=messages,
)
except APIError as e:
if e.status_code in (429, 500, 502, 503) and i < max_retries - 1:
time.sleep(2 ** i) # 指数退避
continue
raise