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

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.

Further reading

Problem with a question

JavaScript · Junior · question 35

Test yourself

Take the JavaScript · Junior quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz