Skip to content

feat(eslint-plugin): add no-throw-literal [extension] #1331

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ module.exports = {
'@typescript-eslint/explicit-function-return-type': 'error',
'@typescript-eslint/no-explicit-any': 'error',
'@typescript-eslint/no-non-null-assertion': 'off',
'@typescript-eslint/no-throw-literal': 'off',
'@typescript-eslint/no-use-before-define': 'off',
'@typescript-eslint/no-var-requires': 'off',
'@typescript-eslint/prefer-nullish-coalescing': 'error',
Expand Down
1 change: 1 addition & 0 deletions packages/eslint-plugin/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,7 @@ Pro Tip: For larger codebases you may want to consider splitting our linting int
| [`@typescript-eslint/no-parameter-properties`](./docs/rules/no-parameter-properties.md) | Disallow the use of parameter properties in class constructors | | | |
| [`@typescript-eslint/no-require-imports`](./docs/rules/no-require-imports.md) | Disallows invocation of `require()` | | | |
| [`@typescript-eslint/no-this-alias`](./docs/rules/no-this-alias.md) | Disallow aliasing `this` | :heavy_check_mark: | | |
| [`@typescript-eslint/no-throw-literal`](./docs/rules/no-throw-literal.md) | Disallow throwing literals as exceptions | | | :thought_balloon: |
| [`@typescript-eslint/no-type-alias`](./docs/rules/no-type-alias.md) | Disallow the use of type aliases | | | |
| [`@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: |
| [`@typescript-eslint/no-unnecessary-qualifier`](./docs/rules/no-unnecessary-qualifier.md) | Warns when a namespace qualifier is unnecessary | | :wrench: | :thought_balloon: |
Expand Down
4 changes: 2 additions & 2 deletions packages/eslint-plugin/ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ It lists all TSLint rules along side rules from the ESLint ecosystem that are th
| [`no-shadowed-variable`] | 🌟 | [`no-shadow`][no-shadow] |
| [`no-sparse-arrays`] | 🌟 | [`no-sparse-arrays`][no-sparse-arrays] |
| [`no-string-literal`] | 🌟 | [`dot-notation`][dot-notation] |
| [`no-string-throw`] | 🌟 | [`no-throw-literal`][no-throw-literal] |
| [`no-string-throw`] | | [`@typescript-eslint/no-throw-literal`] |
| [`no-submodule-imports`] | 🌓 | [`import/no-internal-modules`] (slightly different) |
| [`no-switch-case-fall-through`] | 🌟 | [`no-fallthrough`][no-fallthrough] |
| [`no-this-assignment`] | ✅ | [`@typescript-eslint/no-this-alias`] |
Expand Down Expand Up @@ -510,7 +510,6 @@ Relevant plugins: [`chai-expect-keywords`](https://github.com/gavinaiken/eslint-
[no-shadow]: https://eslint.org/docs/rules/no-shadow
[no-sparse-arrays]: https://eslint.org/docs/rules/no-sparse-arrays
[dot-notation]: https://eslint.org/docs/rules/dot-notation
[no-throw-literal]: https://eslint.org/docs/rules/no-throw-literal
[no-fallthrough]: https://eslint.org/docs/rules/no-fallthrough
[no-unsafe-finally]: https://eslint.org/docs/rules/no-unsafe-finally
[no-unused-expressions]: https://eslint.org/docs/rules/no-unused-expressions
Expand Down Expand Up @@ -603,6 +602,7 @@ Relevant plugins: [`chai-expect-keywords`](https://github.com/gavinaiken/eslint-
[`@typescript-eslint/unified-signatures`]: https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/unified-signatures.md
[`@typescript-eslint/no-misused-new`]: https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/no-misused-new.md
[`@typescript-eslint/no-this-alias`]: https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/no-this-alias.md
[`@typescript-eslint/no-throw-literal`]: https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/no-throw-literal.md
[`@typescript-eslint/no-extraneous-class`]: https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/no-extraneous-class.md
[`@typescript-eslint/no-unused-vars`]: https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/no-unused-vars.md
[`@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
Expand Down
84 changes: 84 additions & 0 deletions packages/eslint-plugin/docs/rules/no-throw-literal.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
# Restrict what can be thrown as an exception (`@typescript-eslint/no-throw-literal`)

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.
The fundamental benefit of `Error` objects is that they automatically keep track of where they were built and originated.

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.

## Rule Details

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.

Examples of **incorrect** code for this rule:

```ts
/*eslint @typescript-eslint/no-throw-literal: "error"*/

throw 'error';

throw 0;

throw undefined;

throw null;

const err = new Error();
throw 'an ' + err;

const err = new Error();
throw `${err}`;

const err = '';
throw err;

function err() {
return '';
}
throw err();

const foo = {
bar: '',
};
throw foo.bar;
```

Examples of **correct** code for this rule:

```ts
/*eslint @typescript-eslint/no-throw-literal: "error"*/

throw new Error();

throw new Error("error");

const e = new Error("error");
throw e;

try {
throw new Error("error");
} catch (e) {
throw e;
}

const err = new Error();
throw err;

function err() {
return new Error();
}
throw err();

const foo = {
bar: new Error();
}
throw foo.bar;

class CustomError extends Error {
// ...
};
throw new CustomError();
```

---

<sup>Taken with ❤️ [from ESLint core](https://github.com/eslint/eslint/blob/master/docs/rules/camelcase.md)</sup>
1 change: 1 addition & 0 deletions packages/eslint-plugin/src/configs/all.json
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@
"@typescript-eslint/no-parameter-properties": "error",
"@typescript-eslint/no-require-imports": "error",
"@typescript-eslint/no-this-alias": "error",
"@typescript-eslint/no-throw-literal": "error",
"@typescript-eslint/no-type-alias": "error",
"@typescript-eslint/no-unnecessary-condition": "error",
"@typescript-eslint/no-unnecessary-qualifier": "error",
Expand Down
2 changes: 2 additions & 0 deletions packages/eslint-plugin/src/rules/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ import noNonNullAssertion from './no-non-null-assertion';
import noParameterProperties from './no-parameter-properties';
import noRequireImports from './no-require-imports';
import noThisAlias from './no-this-alias';
import noThrowLiteral from './no-throw-literal';
import noTypeAlias from './no-type-alias';
import noUnnecessaryCondition from './no-unnecessary-condition';
import noUnnecessaryQualifier from './no-unnecessary-qualifier';
Expand Down Expand Up @@ -115,6 +116,7 @@ export default {
'no-require-imports': noRequireImports,
'no-this-alias': noThisAlias,
'no-type-alias': noTypeAlias,
'no-throw-literal': noThrowLiteral,
'no-unnecessary-condition': noUnnecessaryCondition,
'no-unnecessary-qualifier': noUnnecessaryQualifier,
'no-unnecessary-type-arguments': useDefaultTypeParameter,
Expand Down
119 changes: 119 additions & 0 deletions packages/eslint-plugin/src/rules/no-throw-literal.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
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 {
const symbol = type.getSymbol();
if (symbol?.getName() === 'Error') {
const declarations = symbol.getDeclarations() ?? [];
for (const declaration of declarations) {
const sourceFile = declaration.getSourceFile();
if (program.isSourceFileDefaultLibrary(sourceFile)) {
return true;
}
}
}

const baseTypes = type.getBaseTypes() ?? [];
for (const baseType of baseTypes) {
if (isErrorLike(baseType)) {
return true;
}
}

return false;
}

function tryGetThrowArgumentType(node: TSESTree.Node): ts.Type | null {
switch (node.type) {
case AST_NODE_TYPES.Identifier:
case AST_NODE_TYPES.CallExpression:
case AST_NODE_TYPES.NewExpression:
case AST_NODE_TYPES.MemberExpression: {
const tsNode = parserServices.esTreeNodeToTSNodeMap.get(node);
return checker.getTypeAtLocation(tsNode);
}

case AST_NODE_TYPES.AssignmentExpression:
return tryGetThrowArgumentType(node.right);

case AST_NODE_TYPES.SequenceExpression:
return tryGetThrowArgumentType(
node.expressions[node.expressions.length - 1],
);

case AST_NODE_TYPES.LogicalExpression: {
const left = tryGetThrowArgumentType(node.left);
return left ?? tryGetThrowArgumentType(node.right);
}

case AST_NODE_TYPES.ConditionalExpression: {
const consequent = tryGetThrowArgumentType(node.consequent);
return consequent ?? tryGetThrowArgumentType(node.alternate);
}

default:
return null;
}
}

function checkThrowArgument(node: TSESTree.Node): void {
if (
node.type === AST_NODE_TYPES.AwaitExpression ||
node.type === AST_NODE_TYPES.YieldExpression
) {
return;
}

const type = tryGetThrowArgumentType(node);
if (type) {
if (type.flags & ts.TypeFlags.Undefined) {
context.report({ node, messageId: 'undef' });
return;
}

if (
type.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown) ||
isErrorLike(type)
) {
return;
}
}

context.report({ node, messageId: 'object' });
}

return {
ThrowStatement(node): void {
if (node.argument) {
checkThrowArgument(node.argument);
}
},
};
},
});
Loading
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