I'm a little bit confused about the right way to handle errors in an async
function in javascript.
async function getWeatherAW(woeid) {
try {
const result = await fetch(`https://cors-anywhere.herokuapp.com/https://www.metaweather.com/api/location/${woeid}/`);
const data = await result.json();
const tomorrow = data.consolidated_weather[1];
return data;
} catch(error) {
console.log(`Error catch-Statement: ${error}`);
}
}
const wrongData = 3442;
getWeatherAW(wrongData)
.then(data => {
console.log(data);
})
.catch(error => {
console.log(`Error .catch()-Statement: ${error}`);
})
This code ended up giving this result. I'm curious about why even if the catch-statement is triggered a 404
error is printed out to the console..
Would it also be better to not return the result from the async
function and instead proceed in the function? I mean the data in the then-block seems to be undefinded when an error occurs in first place.. and if I need to call the function more often, I don't always need to write the then
and catch
, right?
Thanks in advance!