54 lines
1.3 KiB
Plaintext
Raw Normal View History

2021-04-28 16:49:39 +02:00
An exception (including ``++reject++``) thrown by a promise will not be caught by a nesting ``++try++`` block, due to the asynchronous nature of execution. Instead, use ``++catch++`` method of ``++Promise++`` or wrap it inside ``++await++`` expression.
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).
2021-04-28 16:49:39 +02:00
== Noncompliant Code Example
2022-02-04 17:28:24 +01:00
[source,javascript]
2021-04-28 16:49:39 +02:00
----
function runPromise() {
return Promise.reject("rejection reason");
}
function foo() {
try { // Noncompliant, the catch clause of the 'try' will not be executed for the code inside promise
runPromise();
} catch (e) {
console.log("Failed to run promise", e);
}
}
----
2021-04-28 16:49:39 +02:00
== Compliant Solution
2022-02-04 17:28:24 +01:00
[source,javascript]
2021-04-28 16:49:39 +02:00
----
function foo() {
runPromise().catch(e => console.log("Failed to run promise", e));
}
// or
async function foo() {
try {
await runPromise();
} catch (e) {
console.log("Failed to run promise", e);
}
}
----
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
include::message.adoc[]
include::highlighting.adoc[]
endif::env-github,rspecator-view[]