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

# 错误码表

> API 错误码完整参考

## HTTP 状态码

| 状态码 | 错误类型                | 说明               |
| --- | ------------------- | ---------------- |
| 200 | -                   | 请求成功             |
| 400 | BadRequest          | 请求参数错误           |
| 401 | Unauthorized        | 认证失败             |
| 403 | Forbidden           | 权限不足             |
| 404 | NotFound            | 资源不存在            |
| 409 | Conflict            | 资源冲突             |
| 429 | TooManyRequests     | 超过速率限制（⚠️ 当前未实现） |
| 500 | InternalServerError | 服务器内部错误          |
| 503 | ServiceUnavailable  | 服务暂时不可用          |

## 错误响应格式

所有错误响应遵循统一格式:

```json theme={null}
{
  "error": "ErrorType",
  "message": "Human-readable error message",
  "details": {
    "key": "additional info"
  },
  "statusCode": 400,
  "correlationId": "req_abc123"
}
```

## 详细错误说明

### 400 Bad Request

#### 缺少必需参数

```json theme={null}
{
  "error": "BadRequest",
  "message": "Missing required field: model",
  "statusCode": 400,
  "correlationId": "req_abc123"
}
```

**原因**: 请求体缺少必需的 `model` 字段

**解决方案**: 确保请求包含所有必需参数

#### 无效的模型 ID

```json theme={null}
{
  "error": "BadRequest",
  "message": "Invalid model format. Expected 'provider/model'",
  "statusCode": 400,
  "correlationId": "req_def456"
}
```

**原因**: 模型 ID 格式不正确

**解决方案**: 使用正确的格式,如 `anthropic/claude-3-7-sonnet-20250219`

#### 缺少工具上下文

```json theme={null}
{
  "error": "BadRequest",
  "message": "Missing required context for tool: zhipin_reply_generator",
  "details": {
    "missingContext": ["configData", "replyPrompts"],
    "tools": ["zhipin_reply_generator"]
  },
  "statusCode": 400,
  "correlationId": "req_ghi789"
}
```

**原因**: 工具缺少必需的上下文参数

**解决方案**:

1. 在 `context` 或 `toolContext` 中提供缺失字段
2. 使用 `contextStrategy: "skip"` 跳过该工具
3. 使用 `GET /api/v1/tools` 查看工具的 `requiredContext`

#### 消息格式错误

```json theme={null}
{
  "error": "BadRequest",
  "message": "Invalid message format. Messages must be an array",
  "statusCode": 400,
  "correlationId": "req_jkl012"
}
```

**原因**: `messages` 字段不是数组格式

**解决方案**: 确保 `messages` 是一个数组,包含 role 和 content 字段

### 401 Unauthorized

#### API Key 无效或缺失

```json theme={null}
{
  "error": "Unauthorized",
  "message": "Invalid or missing API key",
  "statusCode": 401
}
```

<Warning>
  **注意**：401 认证错误在 middleware 层处理,响应中**不包含** `correlationId` 字段,响应头中也**不包含** `X-Correlation-Id`。只有进入 API 路由后的错误（400、403、500 等）才包含 correlationId。
</Warning>

**原因**: API Key 无效、过期或未提供

**解决方案**:

1. 检查 API Key 是否正确
2. 确认 Authorization 头格式: `Bearer YOUR_API_KEY`
3. 验证 API Key 是否已过期
4. 联系管理员重新生成 API Key

#### 认证头格式错误

```json theme={null}
{
  "error": "Unauthorized",
  "message": "Invalid authorization header format",
  "statusCode": 401
}
```

**原因**: Authorization 头格式不正确

**解决方案**: 使用正确格式 `Authorization: Bearer YOUR_API_KEY`

### 403 Forbidden

#### 模型不可用

```json theme={null}
{
  "error": "Forbidden",
  "message": "Model not available with your API key",
  "statusCode": 403,
  "correlationId": "req_stu901"
}
```

**原因**: 请求的模型不在你的许可列表中

**解决方案**:

1. 使用 `GET /api/v1/models` 查看可用模型
2. 联系管理员升级权限
3. 使用许可列表中的其他模型

#### 工具不可用

```json theme={null}
{
  "error": "Forbidden",
  "message": "Tool 'custom_tool' not available with your API key",
  "statusCode": 403,
  "correlationId": "req_vwx234"
}
```

**原因**: 请求的工具不在你的许可列表中

**解决方案**:

1. 使用 `GET /api/v1/tools` 查看可用工具
2. 联系管理员启用该工具
3. 从 `allowedTools` 中移除不可用的工具

### 404 Not Found

```json theme={null}
{
  "error": "NotFound",
  "message": "Endpoint not found",
  "statusCode": 404,
  "correlationId": "req_yzab567"
}
```

**原因**: 请求的端点不存在

**解决方案**:

1. 检查 URL 拼写是否正确
2. 确认使用正确的 HTTP 方法
3. 参考 [API 概览](/api-reference/introduction) 查看所有可用端点

### 409 Conflict

```json theme={null}
{
  "error": "Conflict",
  "message": "A conversation with this ID already exists",
  "statusCode": 409,
  "correlationId": "req_cdef890"
}
```

**原因**: 资源冲突,如重复的会话 ID

**解决方案**: 使用不同的标识符或检查是否已存在

### 429 TooManyRequests（当前未实现）

<Warning>
  **实现状态**：

  * ❌ 当前 API **未实现**速率限制功能
  * ❌ 不会返回 429 错误响应
  * ❌ 不会设置 `Retry-After` 响应头
  * ✅ 错误类型已定义（`TooManyRequests`），但未在代码中使用
  * 💡 如需限流,建议在**网关层或 middleware** 实现
</Warning>

**理论响应格式**（如果实现）：

```json theme={null}
{
  "error": "TooManyRequests",
  "message": "Rate limit exceeded",
  "statusCode": 429,
  "correlationId": "req_ghij123"
}
```

**如果实现,建议的响应头**：

```http theme={null}
Retry-After: 10
```

<Note>
  **设计说明**：如果未来实现限流功能,建议通过 HTTP 响应头 `Retry-After`（单位：秒）传递重试等待时间。
</Note>

**如果实现,建议的客户端处理策略**：

1. 实现指数退避重试策略
2. 读取响应头 `Retry-After` 获取建议的重试时间
3. 减少并发请求数
4. 联系销售团队提升限额

### 500 Internal Server Error

```json theme={null}
{
  "error": "InternalServerError",
  "message": "An unexpected error occurred",
  "statusCode": 500,
  "correlationId": "req_klmn456"
}
```

**原因**: 服务器内部错误

**解决方案**:

1. 使用 `correlationId` 联系技术支持
2. 稍后重试请求
3. 检查服务状态页面

### 503 Service Unavailable

```json theme={null}
{
  "error": "ServiceUnavailable",
  "message": "Service temporarily unavailable. Please try again later.",
  "statusCode": 503,
  "correlationId": "req_opqr789"
}
```

**原因**: 服务暂时不可用(维护、过载等)

**解决方案**:

1. 等待几分钟后重试
2. 实现重试机制
3. 查看服务状态页面

## 特殊错误场景

### 上下文策略错误

使用 `contextStrategy: "error"` 时,缺少上下文会返回:

```json theme={null}
{
  "error": "BadRequest",
  "message": "Missing required context: configData",
  "details": {
    "missingContext": ["configData"],
    "tools": ["zhipin_reply_generator"],
    "strategy": "error"
  },
  "statusCode": 400,
  "correlationId": "req_stuv012"
}
```

### 验证模式报告

使用 `validateOnly: true` 或 `contextStrategy: "report"` 时返回验证报告（不包装在 success/data 中）：

```json theme={null}
{
  "valid": false,
  "model": {
    "valid": true
  },
  "tools": [
    {
      "name": "zhipin_reply_generator",
      "valid": false,
      "missingContext": ["configData", "replyPrompts"]
    }
  ]
}
```

<Note>
  **验证报告说明**：

  * 直接返回 ValidationReport 对象,不包装在 `{success, data}` 中
  * `valid`: 总体验证是否通过
  * `model`: 模型验证结果
  * `tools`: 每个工具的验证结果数组
</Note>

### 流式输出中的错误

流式响应遇到错误时会中断连接。如果错误发生在流开始后,客户端可能会收到部分数据后断开连接。

<Note>
  **流式错误处理**：

  * 流式输出不会返回特殊的错误事件类型
  * 如果验证失败,不会开始流式响应,直接返回 HTTP 错误（400, 401等）
  * 如果流式过程中发生错误,连接会中断,客户端需要实现错误恢复机制
  * 建议在流式请求中实现超时和重试逻辑
</Note>

## 错误处理最佳实践

<AccordionGroup>
  <Accordion title="记录 correlationId">
    每个错误响应都包含 `correlationId`,便于问题排查:

    ```javascript theme={null}
    try {
      const response = await fetch(url, options);
      const data = await response.json();

      if (!response.ok) {
        console.error(`Error [${data.correlationId}]:`, data.message);
        // 记录到日志系统
      }
    } catch (error) {
      console.error('Request failed:', error);
    }
    ```
  </Accordion>

  <Accordion title="实现重试机制">
    对于 5xx 错误实现重试（429 当前未实现,代码为未来兼容性保留）：

    ```javascript theme={null}
    async function fetchWithRetry(url, options, maxRetries = 3) {
      for (let i = 0; i < maxRetries; i++) {
        try {
          const response = await fetch(url, options);

          // 429 处理（当前不会触发,为未来兼容性保留）
          if (response.status === 429) {
            const retryAfter = parseInt(response.headers.get('Retry-After') || '5');
            await sleep(retryAfter * 1000);
            continue;
          }

          if (response.status >= 500) {
            if (i === maxRetries - 1) throw new Error('Server error');
            await sleep(Math.pow(2, i) * 1000); // 指数退避
            continue;
          }

          return response;
        } catch (error) {
          if (i === maxRetries - 1) throw error;
        }
      }
    }
    ```

    <Note>
      **注意**：当前 API 不会返回 429 错误（未实现限流），429 处理逻辑为未来兼容性保留。
    </Note>
  </Accordion>

  <Accordion title="区分错误类型">
    根据状态码采取不同的处理策略:

    ```javascript theme={null}
    function handleError(error) {
      switch (error.statusCode) {
        case 401:
          redirectToLogin(); // 重新认证
          break;
        case 403:
          showPermissionError(); // 权限提示
          break;
        case 429:
          // 当前不会触发,为未来兼容性保留
          scheduleRetry(error.retryAfter || 5);
          break;
        case 500:
        case 503:
          retryWithBackoff(); // 服务器错误重试
          break;
        default:
          showGenericError(error.message);
      }
    }
    ```

    <Note>
      **注意**：当前 API 不会返回 429 错误（未实现限流），case 429 为未来兼容性保留。
    </Note>
  </Accordion>

  <Accordion title="使用 validateOnly 预检">
    在正式调用前验证参数:

    ```javascript theme={null}
    // 先验证
    const validateResponse = await fetch(url, {
      ...options,
      body: JSON.stringify({ ...payload, validateOnly: true })
    });

    const validation = await validateResponse.json();

    if (!validation.data.valid) {
      console.error('Validation failed:', validation.data.errors);
      return; // 不发起实际请求
    }

    // 验证通过,发起实际请求
    const response = await fetch(url, options);
    ```
  </Accordion>
</AccordionGroup>

## 下一步

<CardGroup cols={2}>
  <Card title="错误处理指南" icon="shield" href="/features/error-handling">
    查看完整的错误处理示例代码
  </Card>

  <Card title="调试技巧" icon="bug" href="/best-practices/debugging">
    学习高效的调试方法
  </Card>
</CardGroup>
