From 9dc6da0176c24c8a88867cc13b82896bd89dbf99 Mon Sep 17 00:00:00 2001 From: Alexander T Date: Thu, 12 Dec 2019 18:02:34 +0200 Subject: [PATCH 1/4] feat(eslint-plugin): add no-throw-literal --- .eslintrc.js | 1 + packages/eslint-plugin/README.md | 1 + packages/eslint-plugin/ROADMAP.md | 4 +- .../docs/rules/no-throw-literal.md | 84 +++++ packages/eslint-plugin/src/configs/all.json | 1 + packages/eslint-plugin/src/rules/index.ts | 2 + .../src/rules/no-throw-literal.ts | 125 ++++++++ .../tests/rules/no-throw-literal.test.ts | 290 ++++++++++++++++++ 8 files changed, 506 insertions(+), 2 deletions(-) create mode 100644 packages/eslint-plugin/docs/rules/no-throw-literal.md create mode 100644 packages/eslint-plugin/src/rules/no-throw-literal.ts create mode 100644 packages/eslint-plugin/tests/rules/no-throw-literal.test.ts diff --git a/.eslintrc.js b/.eslintrc.js index 42d8a09253b1..f505a7f012eb 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -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', diff --git a/packages/eslint-plugin/README.md b/packages/eslint-plugin/README.md index 503c06e6894e..bc79d9833592 100644 --- a/packages/eslint-plugin/README.md +++ b/packages/eslint-plugin/README.md @@ -178,6 +178,7 @@ Then you should add `airbnb` (or `airbnb-base`) to your `extends` section of `.e | [`@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 | | | :thought_balloon: | | [`@typescript-eslint/no-unnecessary-qualifier`](./docs/rules/no-unnecessary-qualifier.md) | Warns when a namespace qualifier is unnecessary | | :wrench: | :thought_balloon: | diff --git a/packages/eslint-plugin/ROADMAP.md b/packages/eslint-plugin/ROADMAP.md index 2d4e37bded7e..f631c366b4a6 100644 --- a/packages/eslint-plugin/ROADMAP.md +++ b/packages/eslint-plugin/ROADMAP.md @@ -76,7 +76,7 @@ | [`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`] | @@ -507,7 +507,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 @@ -600,6 +599,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 diff --git a/packages/eslint-plugin/docs/rules/no-throw-literal.md b/packages/eslint-plugin/docs/rules/no-throw-literal.md new file mode 100644 index 000000000000..995465d0310d --- /dev/null +++ b/packages/eslint-plugin/docs/rules/no-throw-literal.md @@ -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(); +``` + +--- + +Taken with ❤️ [from ESLint core](https://github.com/eslint/eslint/blob/master/docs/rules/camelcase.md) diff --git a/packages/eslint-plugin/src/configs/all.json b/packages/eslint-plugin/src/configs/all.json index c3ee46bc95a3..98d9fdadd4d4 100644 --- a/packages/eslint-plugin/src/configs/all.json +++ b/packages/eslint-plugin/src/configs/all.json @@ -47,6 +47,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", diff --git a/packages/eslint-plugin/src/rules/index.ts b/packages/eslint-plugin/src/rules/index.ts index a4dc193e9394..22b9f862d0e5 100644 --- a/packages/eslint-plugin/src/rules/index.ts +++ b/packages/eslint-plugin/src/rules/index.ts @@ -36,6 +36,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'; @@ -113,6 +114,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, diff --git a/packages/eslint-plugin/src/rules/no-throw-literal.ts b/packages/eslint-plugin/src/rules/no-throw-literal.ts new file mode 100644 index 000000000000..a6f70562f603 --- /dev/null +++ b/packages/eslint-plugin/src/rules/no-throw-literal.ts @@ -0,0 +1,125 @@ +import * as ts from 'typescript'; +import * as util from '../util'; +import { + TSESTree, + AST_NODE_TYPES, +} from '@typescript-eslint/experimental-utils'; + +const GLOBAL_ERROR_TYPES = new Set([ + 'ReferenceError', + 'InternalError', + 'SyntaxError', + 'RangeError', + 'EvalError', + 'TypeError', + 'URIError', + 'Error', +]); + +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 checker = parserServices.program.getTypeChecker(); + + function isErrorLike(type: ts.Type): boolean { + if (type.flags & ts.TypeFlags.Object) { + const className = checker.symbolToString(type.symbol); + if (GLOBAL_ERROR_TYPES.has(className)) { + 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); + } + }, + }; + }, +}); diff --git a/packages/eslint-plugin/tests/rules/no-throw-literal.test.ts b/packages/eslint-plugin/tests/rules/no-throw-literal.test.ts new file mode 100644 index 000000000000..589432bd9039 --- /dev/null +++ b/packages/eslint-plugin/tests/rules/no-throw-literal.test.ts @@ -0,0 +1,290 @@ +import rule from '../../src/rules/no-throw-literal'; +import { RuleTester, getFixturesRootDir } from '../RuleTester'; + +const ruleTester = new RuleTester({ + parserOptions: { + ecmaVersion: 2018, + tsconfigRootDir: getFixturesRootDir(), + project: './tsconfig.json', + }, + parser: '@typescript-eslint/parser', +}); + +ruleTester.run('no-throw-literal', rule, { + valid: [ + { + code: `throw new Error();`, + }, + { + code: `throw new Error('error');`, + }, + { + code: `throw Error('error');`, + }, + { + code: ` +const e = new Error(); +throw e; + `, + }, + { + code: ` +try { + throw new Error(); +} catch (e) { + throw e; +} + `, + }, + { + code: ` +function foo() { + return new Error(); +} + +throw foo(); + `, + }, + { + code: ` +const foo = { + bar: new Error() +} + +throw foo.bar; + `, + }, + { + code: ` +const foo = { + bar: new Error() +} + +throw foo['bar']; + `, + }, + { + code: ` +const foo = { + bar: new Error() +} + +const bar = 'bar'; +throw foo[bar]; + `, + }, + { + code: ` +class CustomError extends Error {}; +throw new CustomError(); + `, + }, + { + code: `throw foo = new Error();`, + }, + { + code: `throw 1, 2, new Error();`, + }, + { + code: `throw 'literal' && new Error();`, + }, + { + code: `throw foo ? new Error() : 'literal';`, + }, + { + code: `throw foo ? 'literal' : new Error();`, + }, + { + code: ` +function* foo() { + let index = 0; + throw yield index++; +} + `, + }, + { + code: ` +async function foo() { + throw await bar; +} + `, + }, + ], + invalid: [ + { + code: `throw undefined;`, + errors: [ + { + messageId: 'undef', + }, + ], + }, + { + code: `throw new String('');`, + errors: [ + { + messageId: 'object', + }, + ], + }, + { + code: `throw 'error';`, + errors: [ + { + messageId: 'object', + }, + ], + }, + { + code: `throw 0;`, + errors: [ + { + messageId: 'object', + }, + ], + }, + { + code: `throw false;`, + errors: [ + { + messageId: 'object', + }, + ], + }, + { + code: `throw null;`, + errors: [ + { + messageId: 'object', + }, + ], + }, + { + code: `throw {};`, + errors: [ + { + messageId: 'object', + }, + ], + }, + { + code: `throw 'a' + 'b';`, + errors: [ + { + messageId: 'object', + }, + ], + }, + { + code: ` +const a = ''; +throw a + 'b'; + `, + errors: [ + { + messageId: 'object', + }, + ], + }, + { + code: `throw foo = 'error';`, + errors: [ + { + messageId: 'object', + }, + ], + }, + { + code: `throw new Error(), 1, 2, 3;`, + errors: [ + { + messageId: 'object', + }, + ], + }, + { + code: `throw 'literal' && 'not an Error';`, + errors: [ + { + messageId: 'object', + }, + ], + }, + { + code: `throw foo ? 'not an Error' : 'literal';`, + errors: [ + { + messageId: 'object', + }, + ], + }, + { + code: 'throw `${err}`', + errors: [ + { + messageId: 'object', + }, + ], + }, + { + code: ` +const err = 'error'; +throw err; + `, + errors: [ + { + messageId: 'object', + }, + ], + }, + { + code: ` +function foo(msg) { +} +throw foo('error'); + `, + errors: [ + { + messageId: 'object', + }, + ], + }, + { + code: ` +const foo = { + msg: 'error' +}; +throw foo.msg; + `, + errors: [ + { + messageId: 'object', + }, + ], + }, + { + code: ` +const foo = { + msg: undefined +}; +throw foo.msg; + `, + errors: [ + { + messageId: 'undef', + }, + ], + }, + { + code: ` +class CustomError {} +throw new CustomError(); + `, + errors: [ + { + messageId: 'object', + }, + ], + }, + ], +}); From 9d892e59ab56061047d3183ab73ae5f4cb46d2cc Mon Sep 17 00:00:00 2001 From: Alexander T Date: Thu, 12 Dec 2019 18:02:34 +0200 Subject: [PATCH 2/4] feat(eslint-plugin): add no-throw-literal --- .eslintrc.js | 1 + packages/eslint-plugin/README.md | 1 + packages/eslint-plugin/ROADMAP.md | 4 +- .../docs/rules/no-throw-literal.md | 84 +++++ packages/eslint-plugin/src/configs/all.json | 1 + packages/eslint-plugin/src/rules/index.ts | 2 + .../src/rules/no-throw-literal.ts | 119 +++++++ .../tests/rules/no-throw-literal.test.ts | 297 ++++++++++++++++++ 8 files changed, 507 insertions(+), 2 deletions(-) create mode 100644 packages/eslint-plugin/docs/rules/no-throw-literal.md create mode 100644 packages/eslint-plugin/src/rules/no-throw-literal.ts create mode 100644 packages/eslint-plugin/tests/rules/no-throw-literal.test.ts diff --git a/.eslintrc.js b/.eslintrc.js index 42d8a09253b1..f505a7f012eb 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -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', diff --git a/packages/eslint-plugin/README.md b/packages/eslint-plugin/README.md index 503c06e6894e..bc79d9833592 100644 --- a/packages/eslint-plugin/README.md +++ b/packages/eslint-plugin/README.md @@ -178,6 +178,7 @@ Then you should add `airbnb` (or `airbnb-base`) to your `extends` section of `.e | [`@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 | | | :thought_balloon: | | [`@typescript-eslint/no-unnecessary-qualifier`](./docs/rules/no-unnecessary-qualifier.md) | Warns when a namespace qualifier is unnecessary | | :wrench: | :thought_balloon: | diff --git a/packages/eslint-plugin/ROADMAP.md b/packages/eslint-plugin/ROADMAP.md index 2d4e37bded7e..f631c366b4a6 100644 --- a/packages/eslint-plugin/ROADMAP.md +++ b/packages/eslint-plugin/ROADMAP.md @@ -76,7 +76,7 @@ | [`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`] | @@ -507,7 +507,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 @@ -600,6 +599,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 diff --git a/packages/eslint-plugin/docs/rules/no-throw-literal.md b/packages/eslint-plugin/docs/rules/no-throw-literal.md new file mode 100644 index 000000000000..995465d0310d --- /dev/null +++ b/packages/eslint-plugin/docs/rules/no-throw-literal.md @@ -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(); +``` + +--- + +Taken with ❤️ [from ESLint core](https://github.com/eslint/eslint/blob/master/docs/rules/camelcase.md) diff --git a/packages/eslint-plugin/src/configs/all.json b/packages/eslint-plugin/src/configs/all.json index c3ee46bc95a3..98d9fdadd4d4 100644 --- a/packages/eslint-plugin/src/configs/all.json +++ b/packages/eslint-plugin/src/configs/all.json @@ -47,6 +47,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", diff --git a/packages/eslint-plugin/src/rules/index.ts b/packages/eslint-plugin/src/rules/index.ts index a4dc193e9394..22b9f862d0e5 100644 --- a/packages/eslint-plugin/src/rules/index.ts +++ b/packages/eslint-plugin/src/rules/index.ts @@ -36,6 +36,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'; @@ -113,6 +114,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, diff --git a/packages/eslint-plugin/src/rules/no-throw-literal.ts b/packages/eslint-plugin/src/rules/no-throw-literal.ts new file mode 100644 index 000000000000..5d6fa1d7677e --- /dev/null +++ b/packages/eslint-plugin/src/rules/no-throw-literal.ts @@ -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); + } + }, + }; + }, +}); diff --git a/packages/eslint-plugin/tests/rules/no-throw-literal.test.ts b/packages/eslint-plugin/tests/rules/no-throw-literal.test.ts new file mode 100644 index 000000000000..4e85c591c7d9 --- /dev/null +++ b/packages/eslint-plugin/tests/rules/no-throw-literal.test.ts @@ -0,0 +1,297 @@ +import rule from '../../src/rules/no-throw-literal'; +import { RuleTester, getFixturesRootDir } from '../RuleTester'; + +const ruleTester = new RuleTester({ + parserOptions: { + ecmaVersion: 2018, + tsconfigRootDir: getFixturesRootDir(), + project: './tsconfig.json', + }, + parser: '@typescript-eslint/parser', +}); + +ruleTester.run('no-throw-literal', rule, { + valid: [ + { + code: `throw new Error();`, + }, + { + code: `throw new Error('error');`, + }, + { + code: `throw Error('error');`, + }, + { + code: ` +const e = new Error(); +throw e; + `, + }, + { + code: ` +try { + throw new Error(); +} catch (e) { + throw e; +} + `, + }, + { + code: ` +function foo() { + return new Error(); +} + +throw foo(); + `, + }, + { + code: ` +const foo = { + bar: new Error() +} + +throw foo.bar; + `, + }, + { + code: ` +const foo = { + bar: new Error() +} + +throw foo['bar']; + `, + }, + { + code: ` +const foo = { + bar: new Error() +} + +const bar = 'bar'; +throw foo[bar]; + `, + }, + { + code: ` +class CustomError extends Error {}; +throw new CustomError(); + `, + }, + { + code: ` +class CustomError1 extends Error {} +class CustomError2 extends CustomError1 {} +throw new CustomError(); + `, + }, + { + code: `throw foo = new Error();`, + }, + { + code: `throw 1, 2, new Error();`, + }, + { + code: `throw 'literal' && new Error();`, + }, + { + code: `throw foo ? new Error() : 'literal';`, + }, + { + code: `throw foo ? 'literal' : new Error();`, + }, + { + code: ` +function* foo() { + let index = 0; + throw yield index++; +} + `, + }, + { + code: ` +async function foo() { + throw await bar; +} + `, + }, + ], + invalid: [ + { + code: `throw undefined;`, + errors: [ + { + messageId: 'undef', + }, + ], + }, + { + code: `throw new String('');`, + errors: [ + { + messageId: 'object', + }, + ], + }, + { + code: `throw 'error';`, + errors: [ + { + messageId: 'object', + }, + ], + }, + { + code: `throw 0;`, + errors: [ + { + messageId: 'object', + }, + ], + }, + { + code: `throw false;`, + errors: [ + { + messageId: 'object', + }, + ], + }, + { + code: `throw null;`, + errors: [ + { + messageId: 'object', + }, + ], + }, + { + code: `throw {};`, + errors: [ + { + messageId: 'object', + }, + ], + }, + { + code: `throw 'a' + 'b';`, + errors: [ + { + messageId: 'object', + }, + ], + }, + { + code: ` +const a = ''; +throw a + 'b'; + `, + errors: [ + { + messageId: 'object', + }, + ], + }, + { + code: `throw foo = 'error';`, + errors: [ + { + messageId: 'object', + }, + ], + }, + { + code: `throw new Error(), 1, 2, 3;`, + errors: [ + { + messageId: 'object', + }, + ], + }, + { + code: `throw 'literal' && 'not an Error';`, + errors: [ + { + messageId: 'object', + }, + ], + }, + { + code: `throw foo ? 'not an Error' : 'literal';`, + errors: [ + { + messageId: 'object', + }, + ], + }, + { + code: 'throw `${err}`', + errors: [ + { + messageId: 'object', + }, + ], + }, + { + code: ` +const err = 'error'; +throw err; + `, + errors: [ + { + messageId: 'object', + }, + ], + }, + { + code: ` +function foo(msg) { +} +throw foo('error'); + `, + errors: [ + { + messageId: 'object', + }, + ], + }, + { + code: ` +const foo = { + msg: 'error' +}; +throw foo.msg; + `, + errors: [ + { + messageId: 'object', + }, + ], + }, + { + code: ` +const foo = { + msg: undefined +}; +throw foo.msg; + `, + errors: [ + { + messageId: 'undef', + }, + ], + }, + { + code: ` +class CustomError {} +throw new CustomError(); + `, + errors: [ + { + messageId: 'object', + }, + ], + }, + ], +}); From 8e95494b9318cf8ffbe7cc1681f110772afe6dcc Mon Sep 17 00:00:00 2001 From: Alexander T Date: Thu, 19 Dec 2019 13:23:33 +0200 Subject: [PATCH 3/4] fix(eslint-plugin): [no-throw-literal] fix spelling in docs --- packages/eslint-plugin/docs/rules/no-throw-literal.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/eslint-plugin/docs/rules/no-throw-literal.md b/packages/eslint-plugin/docs/rules/no-throw-literal.md index 995465d0310d..a88720311552 100644 --- a/packages/eslint-plugin/docs/rules/no-throw-literal.md +++ b/packages/eslint-plugin/docs/rules/no-throw-literal.md @@ -1,4 +1,4 @@ -# Restrict what can be thrown as an exception (@typescript-eslint/no-throw-literal) +# 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. From ec3223c51b5127a79544427ca363e451c67e4402 Mon Sep 17 00:00:00 2001 From: Alexander T Date: Thu, 19 Dec 2019 14:22:41 +0200 Subject: [PATCH 4/4] feat(eslint-plugin): [no-throw-literal] improve code coverage --- .../tests/rules/no-throw-literal.test.ts | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/packages/eslint-plugin/tests/rules/no-throw-literal.test.ts b/packages/eslint-plugin/tests/rules/no-throw-literal.test.ts index 4e85c591c7d9..8cec2d66d9dd 100644 --- a/packages/eslint-plugin/tests/rules/no-throw-literal.test.ts +++ b/packages/eslint-plugin/tests/rules/no-throw-literal.test.ts @@ -95,6 +95,9 @@ throw new CustomError(); { code: `throw 'literal' && new Error();`, }, + { + code: `throw new Error() || 'literal'`, + }, { code: `throw foo ? new Error() : 'literal';`, }, @@ -293,5 +296,28 @@ throw new CustomError(); }, ], }, + { + code: ` +class Foo {} +class CustomError extends Foo {} +throw new CustomError(); + `, + errors: [ + { + messageId: 'object', + }, + ], + }, + { + code: ` +const Error = null; +throw Error; + `, + errors: [ + { + messageId: 'object', + }, + ], + }, ], }); 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