JAVASCRIPT
Global Error Handling for Fetch API Requests
Implement a robust, centralized error handling strategy for all Fetch API calls using an interceptor-like pattern, ensuring consistent feedback, logging, and user notifications.
async function handleApiError(error, endpoint) {
console.error(`API Error on ${endpoint}:`, error);
// Centralized error logging (e.g., to a monitoring service)
// sendErrorToMonitoringService(error, endpoint);
// User notification (e.g., toast message)
// displayUserMessage(`Failed to load data from ${endpoint}. Please try again.`, 'error');
// You might rethrow or return a specific error structure
throw error;
}
async function fetchApi(url, options = {}) {
try {
const response = await fetch(url, options);
if (!response.ok) {
let errorData = await response.text();
try {
errorData = JSON.parse(errorData);
} catch (e) { /* not JSON */ }
throw new Error(`Request failed with status ${response.status}: ${JSON.stringify(errorData)}`);
}
return await response.json();
} catch (error) {
return handleApiError(error, url);
}
}
// Example usage:
// fetchApi('https://api.example.com/some-resource')
// .then(data => console.log('Data:', data))
// .catch(error => console.log('Handled Error (main catch):', error.message));
// fetchApi('https://api.example.com/non-existent-resource')
// .then(data => console.log('Data:', data))
// .catch(error => console.log('Handled Error (main catch):', error.message));
How it works: This snippet provides a centralized way to handle errors from Fetch API requests. The `fetchApi` function wraps the native `fetch` call, checking `response.ok` to identify HTTP errors. If an error occurs (either network-related or an HTTP error status), it delegates to the `handleApiError` function. This function can then log the error, display user-friendly messages, or integrate with monitoring services, ensuring consistent error management across all API interactions without duplicating error-handling logic everywhere.