Handling Errors in Promise Chains
by dshilkret
HTML
<div>
Here, we handle errors inside .catch(). If an error occurs, a fallback value ("Default value") is returned and passed on to the next .then().
</div>
JavaScript
const fetchWithError = () => new Promise((resolve, reject) => {
setTimeout(() => reject("Fetching failed"), 1000);
});
fetchWithError()
.then(data => console.log(data))
.catch(error => {
console.error("Error handled:", error);
return "Default value";
})
.then(fallbackData => console.log(fallbackData));