错误处理
使用标准错误代码优雅地处理错误。
错误响应格式
所有API错误遵循一致的JSON格式,包含错误代码和可读消息。
{
"error": {
"code": "error_code_here",
"message": "A human-readable description of the error."
}
}错误代码
| 状态 | 代码 | 描述 |
|---|---|---|
401 | missing_api_key | 请求中未提供X-API-Key标头。 |
401 | invalid_api_key | 提供的API密钥无效、已过期或已撤销。 |
402 | quota_exceeded | 月度请求配额已超限。请升级方案。 |
422 | invalid_image | image字段缺失、非有效base64或超过5MB。 |
422 | invalid_request | 请求体不是有效的JSON。 |
502 | inference_error | ML推理服务暂时不可用。请使用退避重试。 |
错误响应示例
缺少API密钥 (401)
{
"error": {
"code": "missing_api_key",
"message": "No API key provided. Include your key in the X-API-Key header."
}
}无效图像 (422)
{
"error": {
"code": "invalid_image",
"message": "Image exceeds the maximum size of 5 MB."
}
}推理错误 (502)
{
"error": {
"code": "inference_error",
"message": "ML inference service is temporarily unavailable. Please retry."
}
}最佳实践
- 解析响应体之前始终检查HTTP状态码。
- 对502错误实施指数退避(推理服务可能在冷启动)。
- 通过响应标头监控配额使用量以避免意外的402错误。
- 不要重试401或422错误——它们表示需要修复的客户端问题。
- 使用error.code字段进行程序化错误处理,而非消息。
重试示例
以下是带有指数退避的JavaScript示例:
async function analyzePalm(imageBase64, apiKey, retries = 3) {
for (let attempt = 0; attempt < retries; attempt++) {
const res = await fetch(
"https://api.trace-line.site/v1/palm/analyze",
{
method: "POST",
headers: {
"X-API-Key": apiKey,
"Content-Type": "application/json",
},
body: JSON.stringify({ image: imageBase64 }),
}
);
if (res.ok) return res.json();
const error = await res.json();
// Only retry on transient errors
if (res.status !== 502) throw error;
// Exponential backoff: 1s, 2s, 4s
await new Promise((r) =>
setTimeout(r, 1000 * Math.pow(2, attempt))
);
}
throw new Error("Max retries exceeded");
}