Learn how to handle errors gracefully and build resilient integrations.
Use exponential backoff for transient errors (5xx, 429).
Validate all inputs client-side before making API calls.
Respect rate limit headers and implement queuing.
Log all API errors with request IDs for debugging.
// Error handling example (JavaScript)
async function sendSMS(to, message) {
const maxRetries = 3;
let attempt = 0;
while (attempt < maxRetries) {
try {
const response = await fetch('https://api.smsly.cloud/v1/messages', {
method: 'POST',
headers: {
'Authorization': `Bearer ${API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ to, message })
});
if (!response.ok) {
const error = await response.json();
// Handle specific error codes
switch (response.status) {
case 400:
throw new Error(`Invalid request: ${error.message}`);
case 401:
throw new Error('Invalid API key');
case 429:
// Rate limited - wait and retry
const retryAfter = response.headers.get('Retry-After') || 1;
await sleep(retryAfter * 1000);
attempt++;
continue;
case 500:
case 503:
// Server error - retry with backoff
await sleep(Math.pow(2, attempt) * 1000);
attempt++;
continue;
default:
throw new Error(error.message);
}
}
return await response.json();
} catch (error) {
if (attempt === maxRetries - 1) throw error;
attempt++;
}
}
}