Penanganan Error
Tangani error dengan kode error standar.
Format Respons Error
Semua error API mengikuti format JSON yang konsisten.
{
"error": {
"code": "error_code_here",
"message": "A human-readable description of the error."
}
}Kode Error
| Status | Kode | Deskripsi |
|---|---|---|
401 | missing_api_key | Header X-API-Key tidak ada dalam permintaan. |
401 | invalid_api_key | API key tidak valid, kedaluwarsa, atau telah dicabut. |
402 | quota_exceeded | Kuota permintaan bulanan telah terlampaui. |
422 | invalid_image | Field image hilang, base64 tidak valid, atau melebihi 5MB. |
422 | invalid_request | Body permintaan bukan JSON yang valid. |
502 | inference_error | Layanan ML sementara tidak tersedia. Coba lagi dengan backoff. |
Contoh Respons Error
API Key Hilang (401)
{
"error": {
"code": "missing_api_key",
"message": "No API key provided. Include your key in the X-API-Key header."
}
}Gambar Tidak Valid (422)
{
"error": {
"code": "invalid_image",
"message": "Image exceeds the maximum size of 5 MB."
}
}Error Inferensi (502)
{
"error": {
"code": "inference_error",
"message": "ML inference service is temporarily unavailable. Please retry."
}
}Praktik Terbaik
- Selalu periksa kode status HTTP sebelum mem-parsing body respons.
- Terapkan exponential backoff untuk error 502.
- Pantau penggunaan kuota melalui header respons.
- Jangan coba ulang error 401 atau 422.
- Gunakan field error.code untuk penanganan error secara programatis.
Contoh Percobaan Ulang
Contoh JavaScript dengan 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");
}