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

StatusKodeDeskripsi
401missing_api_keyHeader X-API-Key tidak ada dalam permintaan.
401invalid_api_keyAPI key tidak valid, kedaluwarsa, atau telah dicabut.
402quota_exceededKuota permintaan bulanan telah terlampaui.
422invalid_imageField image hilang, base64 tidak valid, atau melebihi 5MB.
422invalid_requestBody permintaan bukan JSON yang valid.
502inference_errorLayanan 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");
}