錯誤處理
錯誤處理
了解 Lawbot AI API 的錯誤回應格式、錯誤碼對照表, 以及建立穩健應用程式的最佳處理策略。
錯誤回應格式
當請求失敗時,API 回傳相應的 HTTP 狀態碼,回應 body 使用 detail欄位說明錯誤原因。HTTP 429(Lifetime 上限)回應格式如下:
429_error.json
{
"detail": {
"error": "lifetime_limit_exceeded",
"model": "lawbot-flash",
"lifetime_requests": 1000,
"lifetime_limit": 1000
}
}401/422 等其他錯誤的 detail 為字串或欄位驗證陣列:
4xx_error.json
{
"detail": "Invalid or missing Bearer token"
}HTTP 狀態碼對照
| 狀態碼 | 錯誤類型 | 說明 | 可重試 |
|---|---|---|---|
| 401 | authentication_error | Bearer Token 無效或已過期 | 否 |
| 422 | unprocessable_entity | 請求主體格式不符,或 messages 清單不含 role='user' 訊息 | 否 |
| 429 | lifetime_limit_exceeded | Lifetime 請求次數已達上限。重試無效,需升級方案。 | 否 |
| 500 | api_error | 伺服器內部錯誤。AI 生成失敗或處理異常。 | 是 |
Python 錯誤處理
error_handling.py
import openai
client = openai.OpenAI(
api_key="YOUR_API_KEY",
base_url="https://developer-api.lawbot.tw/api/v1",
)
try:
response = client.chat.completions.create(
model="lawbot-flash",
messages=[{"role": "user", "content": "..."}],
)
except openai.AuthenticationError as e:
print(f"驗證失敗:{e.message}")
except openai.RateLimitError as e:
# HTTP 429:lifetime 請求次數已達上限,重試無效
print(f"Lifetime 請求次數已達上限,請聯絡 Lawbot 業務團隊:{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: "https://developer-api.lawbot.tw/api/v1"
});
try {
const response = await client.chat.completions.create({
model: "lawbot-flash",
messages: [{ role: "user", content: "..." }],
});
} catch (error) {
if (error instanceof OpenAI.AuthenticationError) {
console.error("驗證失敗:", error.message);
} else if (error instanceof OpenAI.RateLimitError) {
// HTTP 429:lifetime 請求次數已達上限,重試無效
console.error("Lifetime 請求次數已達上限,請聯絡 Lawbot 業務團隊。");
} else if (error instanceof OpenAI.APIError) {
console.error(`API 錯誤 ${error.status}:${error.message}`);
}
}HTTP 429(Lifetime 上限)與 4xx 客戶端錯誤(401、422)均不應重試。 429 代表累計請求次數已達上限,需聯絡 Lawbot 業務團隊升級方案; 4xx 代表 Token 無效或請求格式有誤,需先修正再發送。