错误码
当 API 请求失败时,xmAI 会返回带有相应 HTTP 状态码的 JSON 错误响应。
错误响应格式
所有错误遵循统一格式:
json
{
"error": {
"type": "error_type",
"message": "错误的可读描述",
"code": 401
}
}| 字段 | 类型 | 说明 |
|---|---|---|
type | string | 机器可读的错误类型 |
message | string | 人类可读的错误描述 |
code | number | HTTP 状态码 |
错误类型
| HTTP 状态码 | Type | 说明 |
|---|---|---|
| 401 | unauthorized | 未提供或无效的 API Key |
| 402 | insufficient_balance | 余额不足,需充值 |
| 403 | forbidden | 无权限访问 |
| 429 | rate_limited | 请求频率超限 |
| 503 | model_unavailable / service_unavailable | 模型或服务暂不可用 |
| 500 | internal_error | 内部错误 |
错误响应示例
401 未认证
json
{
"error": {
"type": "unauthorized",
"message": "Invalid API key provided",
"code": 401
}
}402 余额不足
json
{
"error": {
"type": "insufficient_balance",
"message": "Insufficient balance, please top up",
"code": 402
}
}403 无权限
json
{
"error": {
"type": "forbidden",
"message": "You do not have permission to access this resource",
"code": 403
}
}429 请求频率超限
json
{
"error": {
"type": "rate_limited",
"message": "Rate limit exceeded, please retry after 60 seconds",
"code": 429
}
}503 模型不可用
type为model_unavailable表示指定模型无法访问;service_unavailable表示服务层面的通用错误。
json
{
"error": {
"type": "model_unavailable",
"message": "Model gpt-4o is temporarily unavailable, please try again later",
"code": 503
}
}500 内部错误
json
{
"error": {
"type": "internal_error",
"message": "An unexpected error occurred",
"code": 500
}
}错误处理
python
from openai import OpenAI, APIError
client = OpenAI(
api_key="sk-your-xmai-key",
base_url="https://api.xmai.sg/v1",
)
try:
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "你好!"}],
)
except APIError as e:
print(f"错误 {e.status_code}: {e.message}")javascript
import OpenAI from 'openai'
const client = new OpenAI({
apiKey: 'sk-your-xmai-key',
baseURL: 'https://api.xmai.sg/v1',
})
try {
const response = await client.chat.completions.create({
model: 'gpt-4o',
messages: [{ role: 'user', content: '你好!' }],
})
} catch (error) {
if (error instanceof OpenAI.APIError) {
console.log(`错误 ${error.status}: ${error.message}`)
}
}最佳实践
- 401:检查 API Key 是否正确,且已包含在
Authorization请求头中 - 402:前往 console.xmai.sg/wallet 充值余额
- 429:实现指数退避重试逻辑
- 503:尝试使用其他模型,或稍后重试
- 500:如果错误持续出现,请联系客服