Skip to content

Commit 2aa696c

Browse files
a-tarasyukbradzacher
authored andcommitted
feat(eslint-plugin): add no-throw-literal [extension] (typescript-eslint#1331)
1 parent 425f65c commit 2aa696c

File tree

8 files changed

+533
-2
lines changed

8 files changed

+533
-2
lines changed

.eslintrc.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ module.exports = {
2626
'@typescript-eslint/explicit-function-return-type': 'error',
2727
'@typescript-eslint/no-explicit-any': 'error',
2828
'@typescript-eslint/no-non-null-assertion': 'off',
29+
'@typescript-eslint/no-throw-literal': 'off',
2930
'@typescript-eslint/no-use-before-define': 'off',
3031
'@typescript-eslint/no-var-requires': 'off',
3132
'@typescript-eslint/prefer-nullish-coalescing': 'error',

packages/eslint-plugin/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,7 @@ Pro Tip: For larger codebases you may want to consider splitting our linting int
134134
| [`@typescript-eslint/no-parameter-properties`](./docs/rules/no-parameter-properties.md) | Disallow the use of parameter properties in class constructors | | | |
135135
| [`@typescript-eslint/no-require-imports`](./docs/rules/no-require-imports.md) | Disallows invocation of `require()` | | | |
136136
| [`@typescript-eslint/no-this-alias`](./docs/rules/no-this-alias.md) | Disallow aliasing `this` | :heavy_check_mark: | | |
137+
| [`@typescript-eslint/no-throw-literal`](./docs/rules/no-throw-literal.md) | Disallow throwing literals as exceptions | | | :thought_balloon: |
137138
| [`@typescript-eslint/no-type-alias`](./docs/rules/no-type-alias.md) | Disallow the use of type aliases | | | |
138139
| [`@typescript-eslint/no-unnecessary-condition`](./docs/rules/no-unnecessary-condition.md) | Prevents conditionals where the type is always truthy or always falsy | | :wrench: | :thought_balloon: |
139140
| [`@typescript-eslint/no-unnecessary-qualifier`](./docs/rules/no-unnecessary-qualifier.md) | Warns when a namespace qualifier is unnecessary | | :wrench: | :thought_balloon: |

packages/eslint-plugin/ROADMAP.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ It lists all TSLint rules along side rules from the ESLint ecosystem that are th
7979
| [`no-shadowed-variable`] | 🌟 | [`no-shadow`][no-shadow] |
8080
| [`no-sparse-arrays`] | 🌟 | [`no-sparse-arrays`][no-sparse-arrays] |
8181
| [`no-string-literal`] | 🌟 | [`dot-notation`][dot-notation] |
82-
| [`no-string-throw`] | 🌟 | [`no-throw-literal`][no-throw-literal] |
82+
| [`no-string-throw`] | | [`@typescript-eslint/no-throw-literal`] |
8383
| [`no-submodule-imports`] | 🌓 | [`import/no-internal-modules`] (slightly different) |
8484
| [`no-switch-case-fall-through`] | 🌟 | [`no-fallthrough`][no-fallthrough] |
8585
| [`no-this-assignment`] || [`@typescript-eslint/no-this-alias`] |
@@ -510,7 +510,6 @@ Relevant plugins: [`chai-expect-keywords`](https://github.com/gavinaiken/eslint-
510510
[no-shadow]: https://eslint.org/docs/rules/no-shadow
511511
[no-sparse-arrays]: https://eslint.org/docs/rules/no-sparse-arrays
512512
[dot-notation]: https://eslint.org/docs/rules/dot-notation
513-
[no-throw-literal]: https://eslint.org/docs/rules/no-throw-literal
514513
[no-fallthrough]: https://eslint.org/docs/rules/no-fallthrough
515514
[no-unsafe-finally]: https://eslint.org/docs/rules/no-unsafe-finally
516515
[no-unused-expressions]: https://eslint.org/docs/rules/no-unused-expressions
@@ -603,6 +602,7 @@ Relevant plugins: [`chai-expect-keywords`](https://github.com/gavinaiken/eslint-
603602
[`@typescript-eslint/unified-signatures`]: https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/unified-signatures.md
604603
[`@typescript-eslint/no-misused-new`]: https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/no-misused-new.md
605604
[`@typescript-eslint/no-this-alias`]: https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/no-this-alias.md
605+
[`@typescript-eslint/no-throw-literal`]: https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/no-throw-literal.md
606606
[`@typescript-eslint/no-extraneous-class`]: https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/no-extraneous-class.md
607607
[`@typescript-eslint/no-unused-vars`]: https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/no-unused-vars.md
608608
[`@typescript-eslint/no-use-before-define`]: https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/no-use-before-define.md
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
# Restrict what can be thrown as an exception (`@typescript-eslint/no-throw-literal`)
2+
3+
It is considered good practice to only `throw` the `Error` object itself or an object using the `Error` object as base objects for user-defined exceptions.
4+
The fundamental benefit of `Error` objects is that they automatically keep track of where they were built and originated.
5+
6+
This rule restricts what can be thrown as an exception. When it was first created, it only prevented literals from being thrown (hence the name), but it has now been expanded to only allow expressions which have a possibility of being an `Error` object.
7+
8+
## Rule Details
9+
10+
This rule is aimed at maintaining consistency when throwing exception by disallowing to throw literals and other expressions which cannot possibly be an `Error` object.
11+
12+
Examples of **incorrect** code for this rule:
13+
14+
```ts
15+
/*eslint @typescript-eslint/no-throw-literal: "error"*/
16+
17+
throw 'error';
18+
19+
throw 0;
20+
21+
throw undefined;
22+
23+
throw null;
24+
25+
const err = new Error();
26+
throw 'an ' + err;
27+
28+
const err = new Error();
29+
throw `${err}`;
30+
31+
const err = '';
32+
throw err;
33+
34+
function err() {
35+
return '';
36+
}
37+
throw err();
38+
39+
const foo = {
40+
bar: '',
41+
};
42+
throw foo.bar;
43+
```
44+
45+
Examples of **correct** code for this rule:
46+
47+
```ts
48+
/*eslint @typescript-eslint/no-throw-literal: "error"*/
49+
50+
throw new Error();
51+
52+
throw new Error("error");
53+
54+
const e = new Error("error");
55+
throw e;
56+
57+
try {
58+
throw new Error("error");
59+
} catch (e) {
60+
throw e;
61+
}
62+
63+
const err = new Error();
64+
throw err;
65+
66+
function err() {
67+
return new Error();
68+
}
69+
throw err();
70+
71+
const foo = {
72+
bar: new Error();
73+
}
74+
throw foo.bar;
75+
76+
class CustomError extends Error {
77+
// ...
78+
};
79+
throw new CustomError();
80+
```
81+
82+
---
83+
84+
<sup>Taken with ❤️ [from ESLint core](https://github.com/eslint/eslint/blob/master/docs/rules/camelcase.md)</sup>

packages/eslint-plugin/src/configs/all.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@
4949
"@typescript-eslint/no-parameter-properties": "error",
5050
"@typescript-eslint/no-require-imports": "error",
5151
"@typescript-eslint/no-this-alias": "error",
52+
"@typescript-eslint/no-throw-literal": "error",
5253
"@typescript-eslint/no-type-alias": "error",
5354
"@typescript-eslint/no-unnecessary-condition": "error",
5455
"@typescript-eslint/no-unnecessary-qualifier": "error",

packages/eslint-plugin/src/rules/index.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ import noNonNullAssertion from './no-non-null-assertion';
3737
import noParameterProperties from './no-parameter-properties';
3838
import noRequireImports from './no-require-imports';
3939
import noThisAlias from './no-this-alias';
40+
import noThrowLiteral from './no-throw-literal';
4041
import noTypeAlias from './no-type-alias';
4142
import noUnnecessaryCondition from './no-unnecessary-condition';
4243
import noUnnecessaryQualifier from './no-unnecessary-qualifier';
@@ -115,6 +116,7 @@ export default {
115116
'no-require-imports': noRequireImports,
116117
'no-this-alias': noThisAlias,
117118
'no-type-alias': noTypeAlias,
119+
'no-throw-literal': noThrowLiteral,
118120
'no-unnecessary-condition': noUnnecessaryCondition,
119121
'no-unnecessary-qualifier': noUnnecessaryQualifier,
120122
'no-unnecessary-type-arguments': useDefaultTypeParameter,
Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
import * as ts from 'typescript';
2+
import * as util from '../util';
3+
import {
4+
TSESTree,
5+
AST_NODE_TYPES,
6+
} from '@typescript-eslint/experimental-utils';
7+
8+
export default util.createRule({
9+
name: 'no-throw-literal',
10+
meta: {
11+
type: 'problem',
12+
docs: {
13+
description: 'Disallow throwing literals as exceptions',
14+
category: 'Best Practices',
15+
recommended: false,
16+
requiresTypeChecking: true,
17+
},
18+
schema: [],
19+
messages: {
20+
object: 'Expected an error object to be thrown.',
21+
undef: 'Do not throw undefined.',
22+
},
23+
},
24+
defaultOptions: [],
25+
create(context) {
26+
const parserServices = util.getParserServices(context);
27+
const program = parserServices.program;
28+
const checker = program.getTypeChecker();
29+
30+
function isErrorLike(type: ts.Type): boolean {
31+
const symbol = type.getSymbol();
32+
if (symbol?.getName() === 'Error') {
33+
const declarations = symbol.getDeclarations() ?? [];
34+
for (const declaration of declarations) {
35+
const sourceFile = declaration.getSourceFile();
36+
if (program.isSourceFileDefaultLibrary(sourceFile)) {
37+
return true;
38+
}
39+
}
40+
}
41+
42+
const baseTypes = type.getBaseTypes() ?? [];
43+
for (const baseType of baseTypes) {
44+
if (isErrorLike(baseType)) {
45+
return true;
46+
}
47+
}
48+
49+
return false;
50+
}
51+
52+
function tryGetThrowArgumentType(node: TSESTree.Node): ts.Type | null {
53+
switch (node.type) {
54+
case AST_NODE_TYPES.Identifier:
55+
case AST_NODE_TYPES.CallExpression:
56+
case AST_NODE_TYPES.NewExpression:
57+
case AST_NODE_TYPES.MemberExpression: {
58+
const tsNode = parserServices.esTreeNodeToTSNodeMap.get(node);
59+
return checker.getTypeAtLocation(tsNode);
60+
}
61+
62+
case AST_NODE_TYPES.AssignmentExpression:
63+
return tryGetThrowArgumentType(node.right);
64+
65+
case AST_NODE_TYPES.SequenceExpression:
66+
return tryGetThrowArgumentType(
67+
node.expressions[node.expressions.length - 1],
68+
);
69+
70+
case AST_NODE_TYPES.LogicalExpression: {
71+
const left = tryGetThrowArgumentType(node.left);
72+
return left ?? tryGetThrowArgumentType(node.right);
73+
}
74+
75+
case AST_NODE_TYPES.ConditionalExpression: {
76+
const consequent = tryGetThrowArgumentType(node.consequent);
77+
return consequent ?? tryGetThrowArgumentType(node.alternate);
78+
}
79+
80+
default:
81+
return null;
82+
}
83+
}
84+
85+
function checkThrowArgument(node: TSESTree.Node): void {
86+
if (
87+
node.type === AST_NODE_TYPES.AwaitExpression ||
88+
node.type === AST_NODE_TYPES.YieldExpression
89+
) {
90+
return;
91+
}
92+
93+
const type = tryGetThrowArgumentType(node);
94+
if (type) {
95+
if (type.flags & ts.TypeFlags.Undefined) {
96+
context.report({ node, messageId: 'undef' });
97+
return;
98+
}
99+
100+
if (
101+
type.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown) ||
102+
isErrorLike(type)
103+
) {
104+
return;
105+
}
106+
}
107+
108+
context.report({ node, messageId: 'object' });
109+
}
110+
111+
return {
112+
ThrowStatement(node): void {
113+
if (node.argument) {
114+
checkThrowArgument(node.argument);
115+
}
116+
},
117+
};
118+
},
119+
});

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy