JAVASCRIPT
Robust Data Fetching with Error Handling & Cancellation
Implement robust data fetching in JavaScript using async/await, comprehensive error handling, and AbortController for request cancellation to improve user experience.
async function fetchDataWithCancellation(url, options = {}) {
const controller = new AbortController();
const signal = controller.signal;
const timeout = setTimeout(() => controller.abort(), options.timeout || 30000); // Default 30s timeout
try {
const response = await fetch(url, { ...options, signal });
if (!response.ok) {
const errorData = await response.json().catch(() => ({ message: 'Unknown error' }));
throw new Error(`HTTP error! Status: ${response.status}, Message: ${errorData.message || response.statusText}`);
}
return await response.json();
} catch (error) {
if (error.name === 'AbortError') {
console.warn('Fetch request was aborted:', error.message);
throw new Error('Request timed out or was cancelled.');
}
console.error('Fetch error:', error);
throw error;
} finally {
clearTimeout(timeout);
}
}
// Example Usage:
// const abortController = new AbortController(); // If you want to manually abort
// fetchDataWithCancellation('https://api.example.com/data', {
// method: 'GET',
// headers: { 'Content-Type': 'application/json' },
// timeout: 5000, // 5 seconds timeout
// // signal: abortController.signal // Pass if you have an external controller
// })
// .then(data => console.log('Fetched data:', data))
// .catch(error => console.error('Failed to fetch:', error.message));
// // To manually abort after some condition (if not using internal timeout):
// // setTimeout(() => abortController.abort(), 2000);
How it works: This snippet demonstrates how to perform robust API calls using `fetch` with `async/await`. It includes comprehensive error handling for network issues and non-2xx HTTP responses, attempting to parse an error message from the response body. Crucially, it integrates `AbortController` to allow for request cancellation, useful for preventing race conditions or implementing timeouts, thus improving application stability and user experience.