Async/Await Function Not Handling Errors Properly

clock icon

7 months ago Asked

message

1 Answers

eye

11 Views

I have an async/await function in my JavaScript code, but it doesn't seem to be handling errors correctly.

Even when there's an error, it doesn't seem to enter the catch block. What could be the issue, and how can I properly handle errors in async/await functions?

Here's my code:

async function fetchData() {
  try {
    const response = await fetch('https://api.example.com/data');
    const data = await response.json();
    return data;
  } catch (error) {
    console.error('Error:', error);
  }
}

// Usage
fetchData()
  .then((result) => {
    console.log('Data:', result);
  })
  .catch((error) => {
    console.error('Error in promise chain:', error);
  });

1 Answer

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);
});

 

Write your answer here

Top Questions