-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathno-throw-default-error.ts
87 lines (75 loc) · 2.62 KB
/
no-throw-default-error.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import { Rule } from 'eslint';
import type { NewExpression, ThrowStatement } from 'estree';
export const meta = {
hasSuggestions: true,
};
// list of paths that should trigger the toolkit error suggestions
const toolkitErrorPaths = ['packages/aws-cdk/', 'packages/@aws-cdk/toolkit/'];
export function create(context: Rule.RuleContext): Rule.NodeListener {
const fileName = context.filename;
const isToolkitFile = toolkitErrorPaths.some((path) =>
fileName.includes(path),
);
return {
ThrowStatement(node: ThrowStatement) {
if (node.argument.type !== 'NewExpression') {
return;
}
const newExpr = node.argument as NewExpression;
if (
newExpr.callee &&
newExpr.callee.type === 'Identifier' &&
newExpr.callee.name === 'Error'
) {
const suggestions = [];
const replaceErrorClassSuggestion = (suggested: string) => {
return {
desc: `Replace with \`${suggested}\``,
fix: (fixer: Rule.RuleFixer) => {
// no args
if (newExpr.arguments.length === 0) {
return fixer.replaceText(newExpr, `new ${suggested}('<insert error message>')`);
}
return [fixer.replaceText(newExpr.callee, suggested)];
},
};
};
// Adds ToolkitError and AuthenticationError suggestions for CLI files.
if (isToolkitFile) {
suggestions.push(
replaceErrorClassSuggestion('ToolkitError'),
replaceErrorClassSuggestion('AuthenticationError'),
replaceErrorClassSuggestion('AssemblyError'),
replaceErrorClassSuggestion('ContextProviderError'),
);
} else {
suggestions.push({
desc: 'Replace with `ValidationError`',
fix: (fixer: Rule.RuleFixer) => {
// no existing args
if (newExpr.arguments.length === 0) {
return fixer.replaceText(
newExpr,
"new ValidationError('<insert error message>', this)",
);
}
const fixes = [
fixer.replaceText(newExpr.callee, 'ValidationError'),
];
const last = newExpr.arguments.at(-1)?.range;
if (last) {
fixes.push(fixer.insertTextAfterRange(last, ', this'));
}
return fixes;
},
});
}
context.report({
node: newExpr,
message: 'Expected a non-default error object to be thrown.',
suggest: suggestions,
});
}
},
};
}