An exception thrown inside a promise will not be caught by a nesting try
block due to the asynchronous nature of execution.
Promises are designed to propagate errors to the next error handler or catch() block in the promise chain. Promises are asynchronous and operate
outside of the normal call stack. When a Promise is created, it is added to the microtask queue, which is processed after the current call stack has
completed. This means that the try-catch block surrounding the Promise will have already completed by the time the Promise is resolved or rejected.
Therefore, any error occurring within the Promise will not be caught by the try-catch block.
function foo() {
try { // Noncompliant: Promise rejection will not be caught
runPromiseThatRejects();
} catch (e) {
console.log("Failed to run promise", e);
}
}
Instead of using a try-catch block to handle errors in a Promise chain, use the Promise.catch() method. This method allows you to specify a
callback function that will be executed if the Promise is rejected.
function foo() {
runPromiseThatRejects().catch(e => console.log("Failed to run promise", e));
}
Alternatively, wait for the Promise fulfillment value using await
. It is used to unwrap promises and pauses the execution of its
surrounding async
function until the promise is settled (that is, fulfilled or rejected). Any errors that occur within the Promise will
be thrown as exceptions.
async function foo() {
try {
await runPromiseThatRejects();
} catch (e) {
console.log("Failed to run promise", e);
}
}
This rule reports try...catch
statements containing nothing else but call(s) to a function returning a Promise
(thus,
it’s less likely that catch
is intended to catch something else than Promise
rejection).