錯誤處理
錯誤處理
了解 Lawbot AI API 的錯誤回應格式、錯誤碼對照表, 以及建立穩健應用程式的最佳處理策略。
錯誤回應格式
當請求失敗時,API 回傳相應的 HTTP 狀態碼,並在回應 body 中包含error物件:
error.json
{
"error": {
"message": "該模型目前速率受限,請稍後再試。",
"type": "rate_limit_error",
"code": "rate_limit_exceeded",
"param": null
}
}HTTP 狀態碼對照
| 狀態碼 | 錯誤類型 | 說明 | 可重試 |
|---|---|---|---|
| 400 | invalid_request_error | 請求格式錯誤或缺少必要參數 | 否 |
| 401 | authentication_error | API 金鑰無效、過期或未提供 | 否 |
| 403 | permission_error | 金鑰沒有存取該資源的權限 | 否 |
| 404 | not_found_error | 請求的資源或模型不存在 | 否 |
| 422 | unprocessable_entity | 請求語義錯誤,無法處理 | 否 |
| 429 | rate_limit_error | 超過速率限制,請稍後再試 | 是(建議退避) |
| 500 | api_error | 伺服端內部錯誤 | 是 |
| 503 | service_unavailable | 服務暫時不可用 | 是 |
Python 錯誤處理
error_handling.py
import openai
client = openai.OpenAI(
api_key="YOUR_API_KEY",
base_url="http://127.0.0.1:8000",
)
try:
response = client.chat.completions.create(
model="lawbot-pro",
messages=[{"role": "user", "content": "..."}],
)
except openai.AuthenticationError as e:
print(f"驗證失敗:{e.message}")
except openai.RateLimitError as e:
print(f"速率限制:{e.message}")
# 可在此實作指數退避重試
except openai.APIStatusError as e:
print(f"API 錯誤 {e.status_code}:{e.message}")Node.js / TypeScript 錯誤處理
error_handling.ts
import OpenAI from "openai";
const client = new OpenAI({
apiKey: process.env.LAWBOT_API_KEY,
baseURL: "http://127.0.0.1:8000",
});
try {
const response = await client.chat.completions.create({
model: "lawbot-pro",
messages: [{ role: "user", content: "..." }],
});
} catch (error) {
if (error instanceof OpenAI.AuthenticationError) {
console.error("驗證失敗:", error.message);
} else if (error instanceof OpenAI.RateLimitError) {
console.error("速率限制,請稍後再試:", error.message);
} else if (error instanceof OpenAI.APIError) {
console.error(`API 錯誤 ${error.status}:${error.message}`);
}
}指數退避重試策略
遇到 429 或 5xx 錯誤時,建議採用指數退避(Exponential Backoff)策略進行重試:
retry.py
import time
import openai
def chat_with_retry(client, messages, max_retries=3):
"""使用指數退避策略重試請求"""
for attempt in range(max_retries):
try:
return client.chat.completions.create(
model="lawbot-pro",
messages=messages,
)
except openai.RateLimitError:
if attempt == max_retries - 1:
raise
wait_time = 2 ** attempt # 1s, 2s, 4s
print(f"速率限制,{wait_time} 秒後重試...")
time.sleep(wait_time)
except openai.APIStatusError as e:
if e.status_code >= 500:
# 伺服端錯誤可重試
if attempt == max_retries - 1:
raise
time.sleep(2 ** attempt)
else:
raise # 客戶端錯誤不重試4xx 客戶端錯誤(400、401、403、404)通常是請求本身有問題, 重試不會解決問題,應先修正請求內容。