Junior — Senior
Why does an outer try/catch not catch an error thrown inside a Promise
livecode
Task condition
Explain why an exception thrown inside the body of a Promise is not caught by an outer try/catch block.
try {
new Promise((resolve, reject) => {
throw "asda";
});
} catch (e) {
console.log("Error", e);
}
- Inside the
Promiseconstructor, any synchronous errors are automatically converted into a rejected promise, not thrown out as regular exceptions. - A
try/catchblock can only catch errors that are thrown synchronously in the current call stack. An error that becomes a promise rejection will only be handled through.catchmethods,awaitwithtry/catchinside an async function, or a rejection handler when creating the promise. - To catch such an error, you need to add a rejection handler:
new Promise((resolve, reject) => {
throw "asda";
}).catch(err => console.log("Caught", err));
or use async/await:
(async () => {
try {
await new Promise((resolve, reject) => {
throw "asda";
});
} catch (e) {
console.log("Caught", e);
}
})();