Xử lý lỗi
Xử lý lỗi bằng mã lỗi chuẩn.
Định dạng phản hồi lỗi
Tất cả lỗi API tuân theo định dạng JSON nhất quán.
{
"error": {
"code": "error_code_here",
"message": "A human-readable description of the error."
}
}Mã lỗi
| Trạng thái | Mã | Mô tả |
|---|---|---|
401 | missing_api_key | Không có header X-API-Key trong yêu cầu. |
401 | invalid_api_key | API key không hợp lệ, hết hạn hoặc đã bị thu hồi. |
402 | quota_exceeded | Hạn mức yêu cầu hàng tháng đã vượt. Nâng cấp gói. |
422 | invalid_image | Trường image thiếu, base64 không hợp lệ hoặc vượt 5MB. |
422 | invalid_request | Nội dung yêu cầu không phải JSON hợp lệ. |
502 | inference_error | Dịch vụ ML tạm thời không khả dụng. Thử lại với backoff. |
Ví dụ phản hồi lỗi
Thiếu API Key (401)
{
"error": {
"code": "missing_api_key",
"message": "No API key provided. Include your key in the X-API-Key header."
}
}Ảnh không hợp lệ (422)
{
"error": {
"code": "invalid_image",
"message": "Image exceeds the maximum size of 5 MB."
}
}Lỗi suy luận (502)
{
"error": {
"code": "inference_error",
"message": "ML inference service is temporarily unavailable. Please retry."
}
}Thực hành tốt nhất
- Luôn kiểm tra mã trạng thái HTTP trước khi phân tích nội dung phản hồi.
- Triển khai exponential backoff cho lỗi 502.
- Giám sát sử dụng hạn mức qua header phản hồi.
- Không thử lại lỗi 401 hoặc 422.
- Sử dụng trường error.code cho xử lý lỗi theo chương trình.
Ví dụ thử lại
Ví dụ JavaScript với exponential backoff:
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");
}