I’m implementing an asynchronous function to fetch and show JSON data from an API.
In order to handle errors properly, I’m using a try/catch block.
But I’m getting an "Uncaught (in promise)" Error – and I don’t understand why.
This is my code:
const getData = async() => {
const url = "https://dummyjson.com/quotees?limit=20"; // it contains a typo (quotees) intentionally
try {
const res = await fetch(url);
return res.ok ? res.json() : Promise.reject(res.status);
} catch(err) {
console.log(err);
}
};
getData()
.then(d => {
if (d) d.quotes.forEach(q => ...);
});
The output of console.log(err) is "Uncaught (in promise) 404".
Why isn’t it simply "404"?
2
Answers
You return a rejected promise which is unhandled thus raising an error at the global scope. To use your
catch
block just throw:I think you can throw the rejected promise and add a catch block to handle it.
Something like the following should work –