错误处理

Token360 使用兼容 OpenAI 的错误响应格式。所有错误遵循统一的结构,便于在应用中进行处理。

错误响应格式

JSON
1{
2  "error": {
3    "message": "A human-readable description of the error",
4    "type": "error_type",
5    "param": "parameter_name",
6    "code": "error_code"
7  }
8}

字段说明

messagestring错误的详细描述
typestring错误类别(见下表)
paramstring 或 null引发错误的参数名称(如适用)
codestring 或 null机器可读的错误代码

错误类型

invalid_api_keyAPI Key 无效或缺失
invalid_request_error请求格式错误或参数无效
not_found_error请求的资源不存在
model_not_found请求的模型不存在
api_key_frozenAPI Key 已被冻结
model_access_denied没有访问该模型的权限
rate_limit_error在指定时间段内请求过多
insufficient_balance账户余额不足
api_errorToken360 或模型服务的服务端错误

HTTP 状态码

400Bad Request参数无效、缺少必填字段
401UnauthorizedAPI Key 无效、token 已过期
402Payment Required账户余额不足
403ForbiddenAPI Key 已冻结,或无权访问请求的模型
404Not Found模型不存在、资源不存在
429Too Many Requests超过 rate limit 或配额限制
500Internal Server Error服务端错误
502Bad Gateway模型服务不可用
503Service Unavailable服务暂时过载

常见错误及解决方案

401:API Key 无效

JSON
1{
2  "error": {
3    "message": "Invalid API key or token provided",
4    "type": "invalid_api_key",
5    "code": "401"
6  }
7}

解决方法:确认 API Key 正确,并在 Authorization 请求头中包含 Bearer 前缀。

404:模型不存在

JSON
1{
2  "error": {
3    "message": "The requested model does not exist",
4    "type": "model_not_found",
5    "param": "model",
6    "code": "404"
7  }
8}

解决方法:检查模型名称是否正确。使用 GET /v1/models 接口获取可用模型列表。

429:超过 Rate Limit

JSON
1{
2  "error": {
3    "message": "Rate limit exceeded. Please slow down your requests",
4    "type": "rate_limit_error",
5    "code": "429"
6  }
7}

解决方法:实现指数退避重试策略,等待后重试:

Python
1import time
2import random
3
4def call_with_retry(func, max_retries=3):
5    for attempt in range(max_retries):
6        try:
7            return func()
8        except Exception as e:
9            if "rate_limit" in str(e) and attempt < max_retries - 1:
10                wait = (2 ** attempt) + random.random()
11                time.sleep(wait)
12            else:
13                raise

500:服务端内部错误

JSON
1{
2  "error": {
3    "message": "An internal error occurred",
4    "type": "api_error",
5    "code": "500"
6  }
7}

解决方法:这是服务端问题,请稍后重试。如果持续出现,请查看状态页面或联系技术支持。

最佳实践

  1. 始终先检查 HTTP 状态码,再解析响应体。
  2. 4295xx 错误实现指数退避重试
  3. 设置合理的超时时间(标准请求 30 秒,流式请求可适当延长)。
  4. 记录错误响应日志,包括 traceId(如有)——这有助于技术支持排查问题。
  5. 不要重试 400401 错误——这类错误表示请求本身有问题,重试无法解决。

使用 OpenAI SDK 处理错误

OpenAI SDK 提供了类型化的异常类,可以直接捕获:

Python
1from openai import OpenAI, APIError, RateLimitError, AuthenticationError
2
3client = OpenAI(
4    api_key="sk-your-api-key",
5    base_url="https://api.token360.ai/v1"
6)
7
8try:
9    response = client.chat.completions.create(
10        model="glm-5.1",
11        messages=[{"role": "user", "content": "Hello"}]
12    )
13except AuthenticationError:
14    print("Invalid API key")
15except RateLimitError:
16    print("Rate limited - implement backoff")
17except APIError as e:
18    print(f"API error: {e.message}")
此页面对您有帮助吗?