In your code, it appears that you are correctly using async/await to handle promises and fetch data. However, the reason your error handling is not working as expected is because the fetch function does not throw an error for non-2xx HTTP status codes. Instead, it resolves the promise with a Response object representing the response.
To properly handle errors in async/await functions using the fetch API, you need to check the response status manually and throw an error if it is not in the 2xx range. Here's an updated version of your code that handles errors correctly:
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
if (!response.ok) {
throw new Error(`HTTP status code: ${response.status}`);
}
const data = await response.json();
return data;
} catch (error) {
console.error('Error:', error);
throw error; // re-throw the error to propagate it to the catch block in the usage
}
}
// Usage
fetchData()
.then((result) => {
console.log('Data:', result);
})
.catch((error) => {
console.error('Error in promise chain:', error);
});