JavaScript · Junior · Question 35 of 75
Why won't catch catch the error?
try {
fetch("/api").then(r => { throw new Error("fail"); });
} catch (e) {
console.log("caught");
}- ✓Correct answer: The error happens later, asynchronously, after
tryhas already finished - 2
try/catchcan't catchErrorobjects at all - 3
fetchautomatically swallows all errors inside.then
Explanation
The try block ran synchronously and finished before the server responded. Errors in the chain are caught with .catch(), or by writing await fetch(...) inside try in an async function - then catch works.