錯誤處理

錯誤處理

了解 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 狀態碼對照

狀態碼錯誤類型說明可重試
401authentication_errorBearer Token 無效或已過期
422unprocessable_entity請求主體格式不符,或 messages 清單不含 role='user' 訊息
429lifetime_limit_exceededLifetime 請求次數已達上限。重試無效,需升級方案。
500api_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}`);
  }
}