/
no-throw-literal.ts
99 lines (87 loc) · 2.46 KB
/
no-throw-literal.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
88
89
90
91
92
93
94
95
96
97
98
99
import * as ts from 'typescript';
import * as util from '../util';
import {
TSESTree,
AST_NODE_TYPES,
} from '@typescript-eslint/experimental-utils';
export default util.createRule({
name: 'no-throw-literal',
meta: {
type: 'problem',
docs: {
description: 'Disallow throwing literals as exceptions',
category: 'Best Practices',
recommended: false,
requiresTypeChecking: true,
},
schema: [],
messages: {
object: 'Expected an error object to be thrown.',
undef: 'Do not throw undefined.',
},
},
defaultOptions: [],
create(context) {
const parserServices = util.getParserServices(context);
const program = parserServices.program;
const checker = program.getTypeChecker();
function isErrorLike(type: ts.Type): boolean {
if (type.isIntersection()) {
return type.types.some(isErrorLike);
}
if (type.isUnion()) {
return type.types.every(isErrorLike);
}
const symbol = type.getSymbol();
if (!symbol) {
return false;
}
if (symbol.getName() === 'Error') {
const declarations = symbol.getDeclarations() ?? [];
for (const declaration of declarations) {
const sourceFile = declaration.getSourceFile();
if (program.isSourceFileDefaultLibrary(sourceFile)) {
return true;
}
}
}
if (symbol.flags & (ts.SymbolFlags.Class | ts.SymbolFlags.Interface)) {
for (const baseType of checker.getBaseTypes(type as ts.InterfaceType)) {
if (isErrorLike(baseType)) {
return true;
}
}
}
return false;
}
function checkThrowArgument(node: TSESTree.Node): void {
if (
node.type === AST_NODE_TYPES.AwaitExpression ||
node.type === AST_NODE_TYPES.YieldExpression
) {
return;
}
const tsNode = parserServices.esTreeNodeToTSNodeMap.get(node);
const type = checker.getTypeAtLocation(tsNode);
if (type.flags & ts.TypeFlags.Undefined) {
context.report({ node, messageId: 'undef' });
return;
}
if (
util.isTypeAnyType(type) ||
util.isTypeUnknownType(type) ||
isErrorLike(type)
) {
return;
}
context.report({ node, messageId: 'object' });
}
return {
ThrowStatement(node): void {
if (node.argument) {
checkThrowArgument(node.argument);
}
},
};
},
});