JAVASCRIPT
Robust Error Handling for API Fetch Requests
Implement comprehensive error handling for your API calls, catching network issues, HTTP non-2xx responses, and JSON parsing errors for a more reliable user experience.
async function safeFetch(url, options = {}) {
try {
const response = await fetch(url, options);
// Check if the response status is not OK (i.e., 2xx range)
if (!response.ok) {
let errorData = { message: `HTTP error! Status: ${response.status}` };
try {
// Attempt to parse JSON error message from body
errorData = await response.json();
} catch (jsonError) {
// If parsing fails, use default message
console.warn('Could not parse error response as JSON:', jsonError);
}
throw new Error(errorData.message || `Request failed with status ${response.status}`);
}
// Attempt to parse JSON response
try {
return await response.json();
} catch (jsonParseError) {
// Handle cases where response is not valid JSON, but status is OK
if (response.headers.get('Content-Type')?.includes('application/json')) {
console.error('Failed to parse JSON even though Content-Type is application/json:', jsonParseError);
throw new Error('Failed to parse JSON response.');
}
// Return raw text if not JSON, e.g., for success messages
return await response.text();
}
} catch (networkError) {
// Catch network errors (e.g., no internet, CORS issues)
console.error('Network or CORS error:', networkError);
throw new Error('Network error or connection failed. Please check your internet.');
}
}
// Example usage:
// async function loadData() {
// try {
// const data = await safeFetch('https://api.example.com/data');
// console.log('Successfully fetched:', data);
// } catch (error) {
// console.error('Caught error during data load:', error.message);
// // Display error to user
// }
// }
// loadData();
How it works: This snippet provides a comprehensive approach to handling various types of errors that can occur during an API request using the Fetch API. It distinguishes between network errors (caught by `try...catch`), HTTP status errors (non-2xx responses), and JSON parsing errors, offering specific feedback for each scenario to make API integrations more resilient and user-friendly.