@@ -8,7 +8,11 @@ import {
8
8
type RuleResult ,
9
9
createRule ,
10
10
} from "#/utils/rule" ;
11
- import { isInFunctionBody } from "#/utils/tree" ;
11
+ import {
12
+ getEnclosingFunction ,
13
+ getEnclosingTryStatement ,
14
+ isInPromiseHandlerFunction ,
15
+ } from "#/utils/tree" ;
12
16
13
17
/**
14
18
* The name of this rule.
@@ -25,7 +29,7 @@ export const fullName = `${ruleNameScope}/${name}`;
25
29
*/
26
30
type Options = [
27
31
{
28
- allowInAsyncFunctions : boolean ;
32
+ allowToRejectPromises : boolean ;
29
33
} ,
30
34
] ;
31
35
@@ -36,7 +40,7 @@ const schema: JSONSchema4[] = [
36
40
{
37
41
type : "object" ,
38
42
properties : {
39
- allowInAsyncFunctions : {
43
+ allowToRejectPromises : {
40
44
type : "boolean" ,
41
45
} ,
42
46
} ,
@@ -49,7 +53,7 @@ const schema: JSONSchema4[] = [
49
53
*/
50
54
const defaultOptions : Options = [
51
55
{
52
- allowInAsyncFunctions : false ,
56
+ allowToRejectPromises : false ,
53
57
} ,
54
58
] ;
55
59
@@ -84,9 +88,29 @@ function checkThrowStatement(
84
88
context : Readonly < RuleContext < keyof typeof errorMessages , Options > > ,
85
89
options : Readonly < Options > ,
86
90
) : RuleResult < keyof typeof errorMessages , Options > {
87
- const [ { allowInAsyncFunctions } ] = options ;
91
+ const [ { allowToRejectPromises } ] = options ;
92
+
93
+ if ( ! allowToRejectPromises ) {
94
+ return { context, descriptors : [ { node, messageId : "generic" } ] } ;
95
+ }
96
+
97
+ if ( isInPromiseHandlerFunction ( node , context ) ) {
98
+ return { context, descriptors : [ ] } ;
99
+ }
100
+
101
+ const enclosingFunction = getEnclosingFunction ( node ) ;
102
+ if ( enclosingFunction ?. async !== true ) {
103
+ return { context, descriptors : [ { node, messageId : "generic" } ] } ;
104
+ }
88
105
89
- if ( ! allowInAsyncFunctions || ! isInFunctionBody ( node , true ) ) {
106
+ const enclosingTryStatement = getEnclosingTryStatement ( node ) ;
107
+ if (
108
+ ! (
109
+ enclosingTryStatement === null ||
110
+ getEnclosingFunction ( enclosingTryStatement ) !== enclosingFunction ||
111
+ enclosingTryStatement . handler === null
112
+ )
113
+ ) {
90
114
return { context, descriptors : [ { node, messageId : "generic" } ] } ;
91
115
}
92
116
0 commit comments