錯誤處理

錯誤處理

了解 Lawbot AI API 的錯誤回應格式、錯誤碼對照表, 以及建立穩健應用程式的最佳處理策略。

錯誤回應格式

當請求失敗時,API 回傳相應的 HTTP 狀態碼,並在回應 body 中包含error物件:

error.json
{
  "error": {
    "message": "該模型目前速率受限,請稍後再試。",
    "type": "rate_limit_error",
    "code": "rate_limit_exceeded",
    "param": null
  }
}

HTTP 狀態碼對照

狀態碼錯誤類型說明可重試
400invalid_request_error請求格式錯誤或缺少必要參數
401authentication_errorAPI 金鑰無效、過期或未提供
403permission_error金鑰沒有存取該資源的權限
404not_found_error請求的資源或模型不存在
422unprocessable_entity請求語義錯誤,無法處理
429rate_limit_error超過速率限制,請稍後再試是(建議退避)
500api_error伺服端內部錯誤
503service_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  # 客戶端錯誤不重試