错误处理
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}字段说明
message | string | 错误的详细描述 |
type | string | 错误类别(见下表) |
param | string 或 null | 引发错误的参数名称(如适用) |
code | string 或 null | 机器可读的错误代码 |
错误类型
invalid_api_key | API Key 无效或缺失 |
invalid_request_error | 请求格式错误或参数无效 |
not_found_error | 请求的资源不存在 |
model_not_found | 请求的模型不存在 |
api_key_frozen | API Key 已被冻结 |
model_access_denied | 没有访问该模型的权限 |
rate_limit_error | 在指定时间段内请求过多 |
insufficient_balance | 账户余额不足 |
api_error | Token360 或模型服务的服务端错误 |
HTTP 状态码
400 | Bad Request | 参数无效、缺少必填字段 |
401 | Unauthorized | API Key 无效、token 已过期 |
402 | Payment Required | 账户余额不足 |
403 | Forbidden | API Key 已冻结,或无权访问请求的模型 |
404 | Not Found | 模型不存在、资源不存在 |
429 | Too Many Requests | 超过 rate limit 或配额限制 |
500 | Internal Server Error | 服务端错误 |
502 | Bad Gateway | 模型服务不可用 |
503 | Service 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 raise500:服务端内部错误
JSON
1{
2 "error": {
3 "message": "An internal error occurred",
4 "type": "api_error",
5 "code": "500"
6 }
7}解决方法:这是服务端问题,请稍后重试。如果持续出现,请查看状态页面或联系技术支持。
最佳实践
- 始终先检查 HTTP 状态码,再解析响应体。
- 对
429和5xx错误实现指数退避重试。 - 设置合理的超时时间(标准请求 30 秒,流式请求可适当延长)。
- 记录错误响应日志,包括
traceId(如有)——这有助于技术支持排查问题。 - 不要重试
400或401错误——这类错误表示请求本身有问题,重试无法解决。
使用 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}")此页面对您有帮助吗?
上一篇
流式传输
下一篇
创建聊天补全