Skip to content

错误处理 ​

所有错误响应遵循统一结构,每个错误码都附带 code + message + 建议动作,便于自动化处理。

重试黄金法则

认证错误(401)不重试直接上抛;速率限制(429)按 2 ** attempt 秒指数退避后重试;其余 API 错误重试到 max_retries 上限。

错误响应格式 ​

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

json
{ "error": { "code": "error_code", "message": "Human readable error message", "type": "error_type", "param": "optional_parameter_name" } }

HTTP 状态码 ​

状态码含义说明
200成功请求成功处理
400请求错误参数错误或格式不正确
401未认证API Key 无效或缺失
403禁止访问无权限访问该资源
404未找到请求资源不存在
429请求过多超出速率限制
500服务器错误服务器内部错误
502网关错误上游服务不可用
503服务不可用服务暂时不可用

常见错误 ​

按症状快速定位

想从"我遇到了什么报错"出发,附带逐项检查清单,见 故障排查。本页是完整错误码与重试策略的权威参考。
codetypemessage(示例)解决方案
invalid_api_keyauthentication_errorInvalid API key provided检查 Key 是否正确复制、以 sk- 开头、无多余空格
model_not_foundnew_api_error模型 xxx 无可用渠道检查模型名;确认该模型已配置渠道;联系管理员开通权限
insufficient_quotabilling_errorInsufficient quota for this request检查账户余额;联系管理员充值
rate_limit_exceededrate_limit_errorRate limit exceeded. Please slow down.降低请求频率;指数退避重试;申请提高速率限制
context_length_exceededinvalid_request_errorThis model's maximum context length is 8192 tokens减少输入长度;切换更长上下文模型;滑动窗口截断历史

model_not_found 响应体(HTTP 404,type: new_api_error):

json
{
  "error": {
    "code": "model_not_found",
    "message": "模型 gpt-5 无可用渠道",
    "type": "new_api_error"
  }
}

insufficient_quota 响应体(HTTP 402,type: billing_error):

json
{
  "error": {
    "code": "insufficient_quota",
    "message": "Insufficient quota for this request",
    "type": "billing_error"
  }
}

错误处理最佳实践 ​

要点:认证错误(401)不重试直接上抛;速率限制(429)指数退避(2 ** attempt 秒)后重试;其他 API 错误重试到 max_retries 上限。

python
from openai import OpenAI, APIError, RateLimitError, AuthenticationError
import time

client = OpenAI(base_url="https://hub.lurus.cn/v1", api_key="sk-your-api-key")

def chat_with_retry(messages, max_retries=3):
    for attempt in range(max_retries):
        try:
            return client.chat.completions.create(model="deepseek-chat", messages=messages)
        except AuthenticationError as e:
            print(f"Authentication failed: {e}")  # Key 问题,不重试
            raise
        except RateLimitError:
            wait_time = 2 ** attempt
            print(f"Rate limited. Waiting {wait_time}s...")
            time.sleep(wait_time)
        except APIError as e:
            if attempt == max_retries - 1:
                raise
            print(f"API error: {e}. Retrying...")
            time.sleep(1)
    raise Exception("Max retries exceeded")
javascript
import OpenAI from 'openai';

const client = new OpenAI({ baseURL: 'https://hub.lurus.cn/v1', apiKey: 'sk-your-api-key' });

async function chatWithRetry(messages, maxRetries = 3) {
  for (let attempt = 0; attempt < maxRetries; attempt++) {
    try {
      return await client.chat.completions.create({ model: 'deepseek-chat', messages });
    } catch (error) {
      if (error.status === 401) throw error;  // 认证错误,不重试
      if (error.status === 429) {
        const wait = Math.pow(2, attempt) * 1000;
        console.log(`Rate limited. Waiting ${wait}ms...`);
        await new Promise(r => setTimeout(r, wait));
        continue;
      }
      if (attempt === maxRetries - 1) throw error;
      console.log(`Error: ${error.message}. Retrying...`);
      await new Promise(r => setTimeout(r, 1000));
    }
  }
}

联系支持 ​

问题持续?联系 support@lurus.cn

请提供以下信息,便于快速定位:
  • 错误信息完整内容
  • 请求 ID(response header X-Request-ID)
  • 发生时间
  • 复现步骤

下一步

Powered by Lurus Technologies