intermediate Best Practices 15 min 3 steps 10 min read

Handling Errors and Retries

admin

Prerequisites

Understanding Error Responses

All Aelix APIs return errors in a consistent JSON envelope, making it straightforward to parse and handle them programmatically:

{
"error": {
"code": "INVALID_ACCOUNT",
"message": "The specified account ID does not exist or you do not have access.",
"trace_id": "trc_9f3a2b1c",
"documentation_url": "https://aelix.digitalapi.ai/docs/errors#INVALID_ACCOUNT"
}
}

HTTP Status Code Reference

Status Code Meaning
400 BAD_REQUEST Missing or invalid request parameters
401 UNAUTHORIZED Invalid or expired access token
403 FORBIDDEN Token lacks required scope
404 NOT_FOUND Resource does not exist
409 CONFLICT Duplicate resource or state conflict
422 UNPROCESSABLE Validation failed (see errors array)
429 RATE_LIMITED Too many requests — see Retry-After header
500 SERVER_ERROR Internal error — safe to retry with back-off
503 SERVICE_UNAVAILABLE Temporary outage — retry with back-off

Implementing Exponential Back-off

For 429 and 5xx responses, implement retry logic with randomised jitter to avoid thundering-herd problems:

function callWithRetry(url, options, maxRetries = 3) {
for (let attempt = 0; attempt < maxRetries; attempt++) {
const response = await fetch(url, options);

if (response.ok) return response.json();

if (response.status === 429) {
const retryAfter = response.headers.get('Retry-After') || 2 ** attempt;
await sleep(retryAfter * 1000);
continue;
}

if (response.status >= 500) {
const delay = (2 ** attempt) * 1000 + Math.random() * 500;
await sleep(delay);
continue;
}

// 4xx errors — don't retry
const error = await response.json();
throw new Error(error.error.message);
}
throw new Error('Max retries exceeded');
}

Idempotency Keys

For POST requests that modify state (payments, transfers), always include an Idempotency-Key header. This ensures that if you retry due to a network timeout, the operation is only executed once:

POST /v1/payments
Idempotency-Key: pay_20250415_abc123
Content-Type: application/json