Common API Error Codes and Handling Strategies
Understanding API Error Handling in JavaScript
API calls are fundamental to modern web applications, and effective error handling is critical for ensuring robustness and user experience. In JavaScript, when making API requests, encountering errors is inevitable. Properly identifying and resolving these errors allows developers to build resilient systems that can recover from failures and provide meaningful feedback to users.
Common API Error Codes
APIs typically return error codes to indicate the nature of the failure. These codes are standardized and help developers quickly diagnose issues. Below are the most common error codes and their meanings:
4xx Client Errors
These errors indicate that the problem lies on the client side.
400 Bad Request
The request is malformed or invalid. Example: Missing required parameters.fetch('/api/data', { method: 'POST', body: JSON.stringify({ key: 'value' }) }) .then(response => { if (!response.ok) { throw new Error('Bad request'); } });401 Unauthorized
Authentication credentials are missing or invalid.fetch('/api/data', { method: 'GET' }) .then(response => { if (!response.ok) { throw new Error('Unauthorized'); } });
5xx Server Errors
These errors indicate that the server encountered an unexpected issue.
500 Internal Server Error
A generic server error.fetch('/api/data') .then(response => { if (!response.ok) { throw new Error('Internal server error'); } }) .catch(error => { console.error('Server error:', error); });503 Service Unavailable
The server is temporarily unable to handle requests.fetch('/api/data') .then(response => { if (!response.ok) { throw new Error('Service unavailable'); } }) .catch(error => { console.error('Service unavailable:', error); });
4xx Errors
These errors indicate that the client’s request is invalid.
404 Not Found
The requested resource does not exist.fetch('/api/data/123') .then(response => { if (!response.ok) { throw new Error('Not found'); } }) .catch(error => { console.error('Not found:', error); });400 Bad Request
The request is malformed or invalid.fetch('/api/data', { method: 'POST', body: JSON.stringify({ key: 'value' }) }) .then(response => { if (!response.ok) { throw new Error('Bad request'); } });
Handling Strategies
Proper error handling involves logging, retry mechanisms, fallbacks, and client-side validation.
Logging Errors
Capture and log errors to diagnose issues and monitor application health.
fetch('/api/data')
.then(response => {
if (!response.ok) {
console.error('API error:', response.status, response.statusText);
throw new Error('API error');
}
})
.catch(error => {
console.error('Unexpected error:', error);
});
Retry Mechanisms
Implement retry logic for transient errors like 503 Service Unavailable.
function retryRequest(url, maxAttempts = 3) {
return new Promise((resolve, reject) => {
let attempts = 0;
const timeout = 1000 * maxAttempts;
setTimeout(() => {
try {
fetch(url)
.then(response => {
if (response.ok) {
resolve(response);
} else {
reject(new Error('Retry'));
}
})
.catch(error => {
if (attempts < maxAttempts) {
attempts++;
reject(new Error(`Attempt ${attempts} failed`));
} else {
reject(error);
}
});
} catch (error) {
reject(error);
}
}, timeout);
});
}
Fallbacks
Provide alternative responses for failed requests.
fetch('/api/data')
.then(response => {
if (!response.ok) {
return fallbackResponse(response);
}
return response;
})
.catch(error => {
console.error('Fallback triggered:', error);
return fallbackResponse(null);
});
Client-Side Validation
Validate input before making API calls to prevent malformed requests.
function validateRequest(request) {
if (!request || !request.body || !request.body.key) {
throw new Error('Missing required field');
}
return request;
}
Best Practices
- Use proper HTTP methods (GET, POST, PUT, DELETE) to match the API’s intended use.
- Validate and sanitize inputs to prevent malicious requests.
- Implement caching for frequently accessed endpoints.
- Monitor and log errors to identify and resolve issues proactively.
- Use retries for transient errors (e.g., 503, 504).
By understanding and implementing these strategies, developers can build resilient JavaScript applications that handle API errors gracefully and provide a better user experience.