> For the complete documentation index, see [llms.txt](https://docs.blockchainsecurity.asia/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.blockchainsecurity.asia/documentation/he-xin-gai-nian/errors.md).

# 錯誤處理

所有錯誤回應皆使用 error 結構，並保留 meta.request\_id 供除錯、客服與稽核追蹤使用。錯誤時不回傳 data。

請以 error.code 作為程式判斷依據；error.message 僅供顯示、紀錄與人工閱讀，內容可能因語系或版本調整。

## 錯誤信封

```json
{
  "error": {
    "code": "insufficient_credit",
    "message": "insufficient credit: required 5, remaining 2"
  }
}
```

* **`code`** — 穩定的字串代碼，請用它做程式化分支。
* **`message`** — 人類可讀的說明，僅供顯示／記錄，內容可能調整，**請勿**拿來做邏輯判斷。

{% hint style="info" %}
基於安全考量，`500 internal_error` 對外只回傳通用訊息，細節僅記錄在伺服器端。回報時請附上 `X-Request-Id`。
{% endhint %}

## 錯誤碼一覽

| HTTP | code                  | 意義                                | 建議處理                |
| ---: | --------------------- | --------------------------------- | ------------------- |
|  400 | `bad_request`         | 參數缺漏、格式錯誤或請求無法解析                  | 修正請求後重送             |
|  401 | `unauthorized`        | 缺少、格式錯誤、無效或已撤銷的 API key           | 檢查 `X-API-Key`      |
|  403 | `forbidden`           | API key 有效，但無權呼叫該 endpoint 或方案未開通 | 檢查權限或聯絡管理員          |
|  402 | `insufficient_credit` | Credit 餘額不足，無法處理需計費請求             | 加值或調整方案             |
|  404 | `not_found`           | endpoint、資源或查詢目標不存在               | 檢查路徑與參數             |
|  429 | `rate_limited`        | 超過 API key、IP 或 endpoint 的限流規則    | 依 `Retry-After` 後重試 |
|  502 | `upstream_error`      | 上游資料源或後端服務暫時異常                    | 稍後重試                |
|  503 | `service_unavailable` | 服務暫時無法處理，例如維護或佇列已滿                | 稍後重試                |
|  500 | `internal_error`      | 非預期內部錯誤                           | 附 `request_id` 回報   |

## 建議的重試策略

建議的重試策略

* 可安全重試：\
  429、502、503。遇到 429 時請遵守 Retry-After；其他暫時性錯誤建議採用指數退避（exponential backoff）。
* 不建議盲目重試：\
  400、401、403、404。這類錯誤通常代表請求、認證、權限或資源狀態有問題，應先修正後再重送。
* 計費例外：\
  402 insufficient\_credit 在加值或調整方案前，重試通常仍會失敗。

{% hint style="success" %}
計費提醒：Credit 僅在成功且需計費的 2xx 回應中扣除；錯誤回應不會扣點。
{% endhint %}

## 下一步

{% content-ref url="/pages/hauJglYxlKcGMt6ydPim" %}
[限流](/documentation/he-xin-gai-nian/rate-limiting.md)
{% endcontent-ref %}

{% content-ref url="/pages/yecpZZZrz03pEiGYQiNa" %}
[錯誤碼與重試](/documentation/api-can-kao/error-codes.md)
{% endcontent-ref %}
