JAVASCRIPT
Centralized API Error Handling and Notifications
Implement a global error handling mechanism for API requests using custom events, providing consistent error logging and user notifications across your web application.
// apiErrorHandler.js
// Create a custom event for API errors
const API_ERROR_EVENT = 'apiError';
/**
* Dispatches a custom API error event.
* @param {object} error - The error object from the API request.
* @param {string} [message='An unexpected API error occurred.'] - User-friendly message.
*/
function dispatchApiError(error, message = 'An unexpected API error occurred.') {
const event = new CustomEvent(API_ERROR_EVENT, {
detail: { error, message },
bubbles: true, // Allow event to bubble up the DOM
composed: true, // Allow event to traverse shadow DOM boundaries
});
window.dispatchEvent(event); // Dispatch from window for global reach
}
// Example API utility function (can be integrated into your existing fetch/axios)
async function safeFetch(url, options = {}) {
try {
const response = await fetch(url, options);
if (!response.ok) {
const errorData = await response.json().catch(() => ({})); // Try to parse error body
dispatchApiError(
{ status: response.status, url, ...errorData },
`API call failed: ${response.statusText}`
);
throw new Error(`API call failed with status ${response.status}`);
}
return response.json();
} catch (error) {
if (!(error instanceof TypeError) && !error.message.includes('API call failed')) {
// Catch network errors (TypeError) or other unexpected errors
dispatchApiError(error, `Network or unexpected error: ${error.message}`);
}
throw error; // Re-throw to allow component-level handling if needed
}
}
// In your main application file (e.g., App.js or main.js)
// window.addEventListener(API_ERROR_EVENT, (event) => {
// const { error, message } = event.detail;
// console.error('Centralized API Error:', message, error);
// // Display user notification (e.g., a toast, modal)
// // alert(message);
// });
// Usage in a component:
// (async () => {
// try {
// const data = await safeFetch('https://api.example.com/protected');
// console.log('Data:', data);
// } catch (error) {
// console.log('Component caught error, but it was also globally handled.');
// }
// })();
How it works: This snippet demonstrates a centralized approach to handling API errors using custom DOM events. The `safeFetch` function wraps standard `fetch` calls, catches network and HTTP errors, and then dispatches a custom `apiError` event. A global event listener (e.g., attached to `window`) can then intercept these events to log errors, display user notifications (like toast messages), or trigger other global error handling logic, ensuring consistent user feedback and easier debugging across your application.