錯誤處理
所有 API 錯誤回傳統一格式。
錯誤回應格式
Section titled “錯誤回應格式”{ "error": "錯誤訊息描述"}HTTP 狀態碼
Section titled “HTTP 狀態碼”400 Bad Request
Section titled “400 Bad Request”請求參數錯誤。
{ "error": "Invalid date format. Expected YYYY-MM-DD"}常見原因
- 缺少必填參數
- 參數格式錯誤
- 參數值超出範圍
處理方式
- 檢查請求參數
- 參考 API 文件確認格式
401 Unauthorized
Section titled “401 Unauthorized”認證失敗。
{ "error": "Invalid or missing API key"}常見原因
- 未提供 API Key
- API Key 格式錯誤
- API Key 已過期或被刪除
處理方式
- 確認 Header 格式:
Authorization: Bearer YOUR_KEY - 確認 API Key 有效
- 重新產生 API Key
403 Forbidden
Section titled “403 Forbidden”權限不足。
{ "error": "Permission denied"}{ "error": "Insufficient permissions"}{ "error": "Upgrade plan required"}常見原因
- API Key 沒有需要的權限
- 不是該群組的成員
- 角色權限不足(需要 admin 或 owner)
- 功能需要付費方案
處理方式
- 檢查 API Key 權限設定
- 確認群組成員資格
- 升級方案
404 Not Found
Section titled “404 Not Found”資源不存在。
{ "error": "Channel not found"}{ "error": "Message not found"}常見原因
- 群組 ID 不存在
- 訊息已被刪除
- URL 路徑錯誤
處理方式
- 確認資源 ID 正確
- 檢查 URL 路徑
429 Too Many Requests
Section titled “429 Too Many Requests”請求過於頻繁。
{ "error": "Rate limit exceeded", "retryAfter": 60}處理方式
- 等待
retryAfter秒後重試 - 減少請求頻率
- 實作指數退避重試
- 考慮升級方案
500 Internal Server Error
Section titled “500 Internal Server Error”伺服器錯誤。
{ "error": "Internal server error"}處理方式
- 稍後重試
- 如果持續發生,聯繫技術支援
錯誤處理最佳實踐
Section titled “錯誤處理最佳實踐”統一錯誤處理
Section titled “統一錯誤處理”async function apiRequest(url, options = {}) { const response = await fetch(url, { ...options, headers: { 'Authorization': `Bearer ${API_KEY}`, 'Content-Type': 'application/json', ...options.headers, }, });
if (!response.ok) { const error = await response.json(); throw new ApiError(response.status, error.error); }
return response.json();}
class ApiError extends Error { constructor(status, message) { super(message); this.status = status; }}指數退避重試
Section titled “指數退避重試”async function withRetry(fn, maxRetries = 3) { for (let i = 0; i < maxRetries; i++) { try { return await fn(); } catch (error) { if (error.status === 429) { const delay = Math.pow(2, i) * 1000; await new Promise(resolve => setTimeout(resolve, delay)); continue; } throw error; } } throw new Error('Max retries exceeded');}根據狀態碼處理
Section titled “根據狀態碼處理”try { const data = await apiRequest('/api/channels/C123');} catch (error) { switch (error.status) { case 401: // 重新取得 API Key refreshApiKey(); break; case 403: // 顯示權限不足訊息 showPermissionError(); break; case 404: // 資源不存在 showNotFound(); break; case 429: // 稍後重試 scheduleRetry(); break; default: // 一般錯誤 showError(error.message); }}