# 錯誤

來源: https://docs.aicentos.com/zh-TW/billing/errors

Language: zh-TW

> HTTP 狀態碼、錯誤回應結構、常見錯誤與解決方案

aicentos 完全沿用 **OpenAI 錯誤回應格式**。SDK 拋錯時直接 catch 對應的例外即可。

## 錯誤回應結構

所有錯誤回應都是這個格式：

```bash
{
  "error": {
    "message": "你的 API Key 沒有存取 gpt-5 的權限",
    "type": "permission_denied",
    "code": "model_not_allowed",
    "param": "model"
  }
}
```

| 欄位        | 含義             |
| --------- | -------------- |
| `message` | 人類可讀的錯誤描述      |
| `type`    | 錯誤類別（見下表）      |
| `code`    | 細粒度錯誤碼（用於程式判斷） |
| `param`   | 出錯的欄位名稱（如果有）   |

## HTTP 狀態碼速查

| 狀態碼   | 類型                       | 常見原因                      |
| ----- | ------------------------ | ------------------------- |
| `400` | `invalid_request_error`  | 請求主體格式錯誤、參數不合法、model 名稱拼錯 |
| `401` | `authentication_error`   | API 金鑰缺失 / 錯誤 / 已被撤銷      |
| `402` | `insufficient_quota`     | 餘額不足                      |
| `403` | `permission_denied`      | Key 被停用、模型未授權、IP 不在白名單    |
| `404` | `not_found`              | 介面路徑錯誤、模型 ID 錯誤           |
| `408` | `request_timeout`        | 上游逾時（通常 > 60s 無回應）        |
| `413` | `payload_too_large`      | 請求主體過大（圖像、檔案）             |
| `415` | `unsupported_media_type` | Content-Type 不對           |
| `422` | `invalid_request_error`  | 請求主體能解析但語意不對              |
| `429` | `rate_limit_exceeded`    | 觸發限流，降低請求頻率後重試            |
| `500` | `server_error`           | 平台內部錯誤（罕見）                |
| `502` | `bad_gateway`            | 上游服務異常                    |
| `503` | `service_unavailable`    | 上游過載，建議稍後重試               |
| `504` | `gateway_timeout`        | 上游回應逾時                    |

## 常見錯誤與解決

### 401 — Invalid API key

```bash
{ "error": { "message": "Incorrect API key provided", "type": "authentication_error" } }
```

**檢查清單**：

* `Authorization` 標頭是不是 `Bearer sk-xxx` 格式（注意有空格）
* Key 是不是從控制台複製時帶了空格 / 換行
* Key 是不是已刪除 / 已停用 / 已過期
* 是不是把測試 Key 提交到正式環境了

### 402 — Insufficient quota

```bash
{ "error": { "message": "Insufficient quota", "type": "insufficient_quota" } }
```

儲值 → 控制台「錢包管理」。開啟 [餘額預警](https://docs.aicentos.com/zh-TW/billing/pricing#%E9%A4%98%E9%A1%8D%E9%A0%90%E8%AD%A6) 避免再次發生。

### 403 — Model not allowed

```bash
{ "error": { "message": "Model gpt-5 not allowed for this key", "code": "model_not_allowed" } }
```

建立權杖時勾選了「**可用模型**」白名單，請求的 model 不在其中。修改權杖設定或換 Key。

### 404 — Model not found

```bash
{ "error": { "message": "The model 'gpt-4-turbo-2024-04-09' does not exist", "code": "model_not_found" } }
```

模型 ID 拼錯或已下線。到[模型廣場](https://aicentos.com/pricing)確認目前可用的 ID。

### 429 — Rate limit exceeded

回應標頭 `Retry-After` 會告訴你幾秒後重試。降低並行數與請求頻率即可恢復。

### 500 / 502 / 503 — 服務異常

通常是上游波動。**自動重試 2-3 次**通常能成功。如果持續 5 分鐘以上：

* 查 [狀態頁](https://status.aicentos.com)（如有）
* 聯絡客服

### 408 / 504 — 逾時

請求超過 60s 無回應。常見原因：

* prompt 太長，讓模型「思考」逾時
* 串流輸出未啟用（長回應建議加 `stream: true`）

**解決方式**：

* 縮短 prompt
* 開啟串流：`{ "model": "...", "messages": [...], "stream": true }`
* 切換到更快的模型（例如從 `gpt-4o` 換成 `gpt-4o-mini`）

## SDK 錯誤處理範例

```bash
export AICENTOS_API_KEY="sk-your-aicentos-api-key"
```

### Python

```python
import os
from openai import OpenAI, APIError, RateLimitError, AuthenticationError

client = OpenAI(api_key=os.environ["AICENTOS_API_KEY"], base_url="https://aicentos.com/v1")

try:
    resp = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[{"role": "user", "content": "hi"}],
    )
except AuthenticationError:
    print("Key 錯了")
except RateLimitError as e:
    print(f"被限流，{e.response.headers.get('Retry-After')}s 後重試")
except APIError as e:
    print(f"其他 API 錯誤：{e.status_code} {e.message}")
```

### Node.js

```js
import OpenAI, { APIError } from 'openai';

const client = new OpenAI({
  apiKey: process.env.AICENTOS_API_KEY,
  baseURL: 'https://aicentos.com/v1',
});

try {
  const resp = await client.chat.completions.create({ ... });
} catch (err) {
  if (err instanceof APIError) {
    console.log(err.status, err.code, err.message);
  }
}
```

## 重試與降級建議

| 錯誤類型                                  | 建議處理                    |
| ------------------------------------- | ----------------------- |
| `400` / `401` / `402` / `403` / `404` | **不重試**，程式碼 / 設定錯誤，先檢查  |
| `429`                                 | 依 `Retry-After` 重試，指數退避 |
| `500` / `502` / `503` / `504` / `408` | 立即重試 1-3 次，間隔 1-5s      |

OpenAI 官方 SDK 預設有合理的重試策略，**正式環境程式碼直接用 SDK，不要自己寫 fetch**。