معالجة الأخطاء
عالج الأخطاء بشكل صحيح باستخدام رموز الخطأ القياسية.
تنسيق استجابة الخطأ
تتبع جميع أخطاء 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.
- راقب استخدام الحصة عبر رؤوس الاستجابة.
- لا تعد محاولة أخطاء 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");
}