> ## Documentation Index
> Fetch the complete documentation index at: https://docs.sorsa.io/llms.txt
> Use this file to discover all available pages before exploring further.

# 错误码

> 了解 Sorsa API 从 400 到 500 各状态码的含义、原因和解决方法。

请求失败时，Sorsa 会返回标准 HTTP 状态码，以及包含 `message` 字段的 JSON 请求响应体，用于说明问题。本页介绍可能遇到的状态码、原因和处理方法。

## 错误响应格式

所有错误响应都采用相同结构：

```json theme={null}
{
  "message": "ApiKey required"
}
```

`message` 字段提供可读的错误说明。调试时请先查看它，通常能直接找到问题所在。

## 快速参考

| 状态码 | 类型    | 含义                 |
| :-- | :---- | :----------------- |
| 200 | 成功    | 请求成功完成             |
| 400 | 客户端错误 | 请求无效：参数缺失或无效       |
| 401 | 客户端错误 | 未授权：身份验证失败         |
| 403 | 客户端错误 | 禁止访问：密钥有效，但没有权限或额度 |
| 404 | 客户端错误 | 未找到：资源不存在或为私有      |
| 429 | 客户端错误 | 请求过多：超过速率限制        |
| 500 | 服务器错误 | 内部错误：服务端出现问题       |

## 400 Bad Request

请求包含无效或缺失参数，因此无法处理。

**常见原因**

* 缺少必选参数，例如 `link`、`id`、`username` 或 `query`
* 参数类型或格式错误，例如本应是数字却传入字符串
* POST 请求的 JSON 请求体格式错误或为空

**解决方法：** 在 [API 参考](https://docs.sorsa.io/zh-Hans/api-reference-guide)中查看所调用端点，确认所有必选参数齐全且格式正确。POST 请求需要设置 `Content-Type: application/json`，并确保请求体是有效 JSON。

## 401 Unauthorized

身份验证失败，API 无法识别你的账号。

**常见原因**

* 完全缺少 `ApiKey` 请求头
* 请求头名称拼写错误。请使用 `ApiKey`；HTTP 请求头名称不区分大小写，但 `Api-Key` 和 `api_key` 是不同名称
* 密钥值错误、复制时带入多余空白，或对应密钥已被删除

**解决方法：** 确认请求发送 `ApiKey: your_key_here`，并在[控制台](https://api.sorsa.io/overview/keys)检查密钥仍有效。不确定时，直接从控制台重新复制密钥。详情请参阅[身份验证](https://docs.sorsa.io/zh-Hans/authentication)。

## 403 Forbidden

API 密钥有效，但请求被拒绝。

**常见原因**

* 请求配额耗尽，剩余 0 次
* 订阅已过期

**解决方法：** 通过 `GET /key-usage-info` 或[控制台](https://api.sorsa.io/overview)检查余额。请求次数用完时，可在[账单](https://api.sorsa.io/overview/billing)页面充值或升级。

## 404 Not Found

请求的资源不存在。

**常见原因**

* X 用户更改了用户名、删除账号或被停用
* 作者删除了推文
* 账号或推文为私有（受保护），而 Sorsa 只能访问公开数据
* 端点 URL 本身有误

**解决方法：** 确认用户或推文仍存在，并可在 X 上公开访问。用户名更改时用户 ID 保持不变。如果已保存用户 ID，可通过 `/id-to-username/{user_id}` 查询当前用户名，或直接将 `user_id` 传给支持它的端点。

## 429 Too Many Requests

你已超过每秒 20 次请求的速率限制。

**常见原因**

* 在没有延迟的紧密循环中发送请求
* 多个并行工作进程共享一个 API 密钥

**解决方法：** 在请求之间加入小延迟（50ms 可控制单个串行进程的节奏；共享密钥需要统一协调），或加入暂停一秒后的重试逻辑。策略和代码示例请参阅[速率限制](https://docs.sorsa.io/zh-Hans/rate-limits)。

## 500 Internal Server Error

服务端出现问题。

**处理方式**

* 短暂等待 1–2 秒后重试。临时的 500 错误通常会自行恢复。
* 如果多次重试仍失败，或影响多个端点，请在[状态页面](https://uptime.sorsa.io/status/v3)检查是否有故障。
* 如果问题持续，通过 [contacts@sorsa.io](mailto:contacts@sorsa.io) 或 [Discord](https://discord.com/invite/uwAefKCj7X) 联系支持团队，提供端点 URL、请求体和大致时间。请从诊断材料中移除 API 密钥和身份验证请求头。

## 在代码中处理错误

稳健的集成应妥善处理各类错误码，而不是遇到意外响应就崩溃。以下是可复用的 Python 和 JavaScript 模式。

**Python**

```python theme={null}
import time
import requests

def sorsa_request(method, endpoint, api_key, params=None, json_body=None, max_attempts=3):
    """GET/POST data retrieval with bounded retries; max_attempts includes the first call."""
    method = method.upper()
    if method not in {"GET", "POST"}:
        raise ValueError("Use GET or POST")
    if max_attempts < 1:
        raise ValueError("max_attempts must be positive")
    url = f"https://api.sorsa.io/v3{endpoint}"

    for attempt in range(max_attempts):
        try:
            response = requests.request(
                method, url, headers={"ApiKey": api_key},
                params=params, json=json_body, timeout=30,
            )
        except (requests.Timeout, requests.ConnectionError):
            if attempt + 1 == max_attempts:
                raise
        else:
            if response.ok:
                return response.json()
            retryable = response.status_code == 429 or response.status_code >= 500
            if not retryable or attempt + 1 == max_attempts:
                try:
                    message = response.json().get("message", response.reason)
                except (ValueError, AttributeError):
                    message = response.reason
                raise requests.HTTPError(
                    f"HTTP {response.status_code}: {message}", response=response,
                )
        time.sleep(min(2 ** attempt, 8))

data = sorsa_request("GET", "/info", "YOUR_API_KEY", params={"username": "elonmusk"})
print(data["display_name"])
```

**JavaScript**

```javascript theme={null}
async function sorsaRequest(method, endpoint, apiKey, body = null, maxAttempts = 3) {
  method = method.toUpperCase();
  if (!["GET", "POST"].includes(method)) throw new Error("Use GET or POST");
  if (!Number.isInteger(maxAttempts) || maxAttempts < 1) {
    throw new Error("maxAttempts must be a positive integer");
  }
  if (method === "GET" && body !== null) throw new Error("Use query parameters for GET");
  const url = `https://api.sorsa.io/v3${endpoint}`;
  const options = { method, headers: { ApiKey: apiKey } };
  if (body !== null) {
    options.headers["Content-Type"] = "application/json";
    options.body = JSON.stringify(body);
  }

  for (let attempt = 0; attempt < maxAttempts; attempt++) {
    let response;
    try {
      response = await fetch(url, { ...options, signal: AbortSignal.timeout(30000) });
    } catch (error) {
      if (attempt + 1 === maxAttempts) throw error;
      await new Promise((r) => setTimeout(r, Math.min(2 ** attempt, 8) * 1000));
      continue;
    }
    if (response.ok) return await response.json();
    const retryable = response.status === 429 || response.status >= 500;
    if (!retryable || attempt + 1 === maxAttempts) {
      let message = response.statusText;
      try { message = (await response.json()).message || message; } catch {}
      throw new Error(`HTTP ${response.status}: ${message}`);
    }
    await new Promise((r) => setTimeout(r, Math.min(2 ** attempt, 8) * 1000));
  }
}

const data = await sorsaRequest("GET", "/info?username=elonmusk", "YOUR_API_KEY");
console.log(data.display_name);
```

这些示例会重试网络超时、连接失败、`429` 和 `5xx` 响应，默认最多尝试三次。其他 HTTP 错误会立即失败。成功响应如果包含无效 JSON，也会报错以便检查。JavaScript 需要 Node.js 18+；Python 需先安装 `requests` 包。

## 后续步骤

* [速率限制](https://docs.sorsa.io/zh-Hans/rate-limits)：保持每秒 20 次以内的策略
* [分页](https://docs.sorsa.io/zh-Hans/pagination)：正确获取大规模数据集
* [API 参考](https://docs.sorsa.io/zh-Hans/api-reference-guide)：完整端点列表与参数结构
