JAVASCRIPT
Gracefully Handling Specific HTTP Error Status Codes with Fetch
Learn to interpret and respond to specific HTTP status codes (e.g., 401, 404, 500) from API responses using JavaScript's fetch API for robust error management.
async function fetchDataWithStatusCodeHandling(url) {
try {
const response = await fetch(url);
if (response.ok) {
return await response.json();
} else {
switch (response.status) {
case 400:
console.error('Bad Request: The server could not understand the request due to invalid syntax.');
const errorDetails = await response.json();
console.error('Details:', errorDetails);
throw new Error('Bad Request: ' + JSON.stringify(errorDetails));
case 401:
console.error('Unauthorized: Authentication is required and has failed or has not yet been provided.');
// Example: Redirect to login page or refresh token
// window.location.href = '/login';
throw new Error('Unauthorized');
case 403:
console.error('Forbidden: The client does not have access rights to the content.');
throw new Error('Forbidden');
case 404:
console.error('Not Found: The server can not find the requested resource.');
throw new Error('Resource Not Found');
case 500:
console.error('Internal Server Error: Something went wrong on the server.');
throw new Error('Internal Server Error');
default:
console.error(`Unhandled HTTP error! Status: ${response.status} - ${response.statusText}`);
throw new Error(`API Error: ${response.status}`);
}
}
} catch (error) {
console.error('Network or other error:', error);
throw error;
}
}
// Usage example:
// fetchDataWithStatusCodeHandling('https://api.example.com/secure-data')
// .then(data => console.log('Data fetched:', data))
// .catch(err => console.error('Failed to process data:', err.message));
How it works: This snippet demonstrates how to gracefully handle various HTTP error status codes returned by an API. Instead of a generic error message, it uses a `switch` statement to provide specific error logging, user feedback, or actions (like redirecting to a login page) based on common status codes such as 400 (Bad Request), 401 (Unauthorized), 403 (Forbidden), 404 (Not Found), and 500 (Internal Server Error). This enhances the robustness and user-friendliness of web applications.