JAVASCRIPT
Robust Error Handling for Fetch API Requests
Enhance your web applications by implementing comprehensive error handling for `fetch` API requests, distinguishing between network, HTTP, and JSON parsing errors for reliability.
async function robustFetch(url, options = {}) {
try {
const response = await fetch(url, options);
if (!response.ok) {
// Attempt to read error message from response body
let errorMessage = `HTTP error! status: ${response.status}`;
try {
const errorData = await response.json();
errorMessage = errorData.message || JSON.stringify(errorData);
} catch (jsonError) {
// If response is not JSON, use default message or raw text
errorMessage = await response.text() || errorMessage;
}
throw new Error(errorMessage);
}
// Check if response has content and is JSON before parsing
const contentType = response.headers.get('content-type');
if (contentType && contentType.includes('application/json')) {
const data = await response.json();
return data;
} else {
// If not JSON, return raw text or a success indicator
return await response.text();
}
} catch (error) {
// Distinguish between network errors and HTTP errors
if (error.name === 'TypeError' && error.message === 'Failed to fetch') {
console.error('Network Error: Could not connect to the API.', error);
throw new Error('Network Error: Please check your internet connection.');
} else {
console.error('API Request Error:', error.message);
throw error; // Re-throw to allow caller to handle
}
}
}
// Usage example:
// robustFetch('https://api.example.com/non-existent-endpoint')
// .then(data => console.log('Success:', data))
// .catch(error => console.error('Caught error:', error.message));
// robustFetch('https://api.example.com/data')
// .then(data => console.log('Data received:', data))
// .catch(error => console.error('Caught error:', error.message));
How it works: This snippet provides a more robust error handling strategy for `fetch` API requests. It differentiates between network errors (e.g., 'Failed to fetch'), non-OK HTTP responses (e.g., 404, 500), and attempts to parse error messages from the API's response body. It also handles cases where the response might not be JSON, providing a comprehensive approach to API request reliability.