JAVASCRIPT
Robust Data Fetching with Async/Await
Learn to fetch data from APIs using modern JavaScript `async/await` syntax, including comprehensive error handling for network issues and API response errors.
async function fetchData(url, options = {}) {
try {
const response = await fetch(url, options);
if (!response.ok) {
// Handle HTTP errors
const errorBody = await response.json().catch(() => ({ message: 'Failed to parse error response' }));
throw new Error(`HTTP error! Status: ${response.status}, Message: ${errorBody.message || response.statusText}`);
}
return await response.json();
} catch (error) {
// Handle network errors or errors thrown above
console.error("Error fetching data:", error);
// Re-throw or return a specific error structure to the caller
throw error;
}
}
// Example Usage:
// fetchData('https://api.example.com/data')
// .then(data => console.log('Fetched data:', data))
// .catch(err => console.error('Failed to fetch:', err.message));
// fetchData('https://api.example.com/posts', {
// method: 'POST',
// headers: { 'Content-Type': 'application/json' },
// body: JSON.stringify({ title: 'New Post', content: 'Lorem ipsum' })
// })
// .then(data => console.log('Created post:', data))
// .catch(err => console.error('Failed to create post:', err.message));
How it works: This snippet demonstrates how to perform API requests using JavaScript's `fetch` API with `async/await` for cleaner asynchronous code. It includes robust error handling to catch network failures and non-2xx HTTP responses, attempting to parse an error message from the response body if available. This pattern ensures that API calls are resilient and provide clear feedback on failure.