Proper error handling is essential for a reliable bot. This guide covers common error codes, best practices, and how to handle failures gracefully.
Common Error Codes
Bad Request
Invalid parameters or malformed request
Check your request body and parameters
Unauthorized
Missing or invalid authentication
Verify your API token is valid and not expired
Forbidden
Insufficient permissions
Check user role and resource access permissions
Not Found
Resource doesn't exist
Verify the resource ID and endpoint path
Rate Limited
Too many requests
Implement backoff and reduce request frequency
Server Error
Internal server error
Retry the request or contact support
Best Practices
Implement Retries
Use exponential backoff for transient failures. Start with 1s, then 2s, 4s, etc.
User-Friendly Messages
Show helpful error messages to users, not raw error codes.
Log Errors
Log all errors with context for debugging. Include request IDs.
Fail Gracefully
Handle errors without crashing. Provide fallback behavior.
Example: Retry Logic
async function apiCallWithRetry(fn, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
return await fn();
} catch (error) {
if (error.status === 429 || error.status >= 500) {
const delay = Math.pow(2, i) * 1000;
await sleep(delay);
continue;
}
throw error;
}
}
throw new Error('Max retries exceeded');
}