diff --git a/.eslintrc.js b/.eslintrc.js index 42d8a09253b..f505a7f012e 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 0891413add3..586d43d0aa0 100644 --- a/packages/eslint-plugin/README.md +++ b/packages/eslint-plugin/README.md @@ -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: | diff --git a/packages/eslint-plugin/ROADMAP.md b/packages/eslint-plugin/ROADMAP.md index 34d39685348..bca59dc84cf 100644 --- a/packages/eslint-plugin/ROADMAP.md +++ b/packages/eslint-plugin/ROADMAP.md @@ -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`] | @@ -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 @@ -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 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 00000000000..a8872031155 --- /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 00a164e1dfc..b350f86de39 100644 --- a/packages/eslint-plugin/src/configs/all.json +++ b/packages/eslint-plugin/src/configs/all.json @@ -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", diff --git a/packages/eslint-plugin/src/rules/index.ts b/packages/eslint-plugin/src/rules/index.ts index ee66fbc8a35..a14884bbbd8 100644 --- a/packages/eslint-plugin/src/rules/index.ts +++ b/packages/eslint-plugin/src/rules/index.ts @@ -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'; @@ -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, 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 00000000000..5d6fa1d7677 --- /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 00000000000..8cec2d66d9d --- /dev/null +++ b/packages/eslint-plugin/tests/rules/no-throw-literal.test.ts @@ -0,0 +1,323 @@ +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 new Error() || 'literal'`, + }, + { + 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', + }, + ], + }, + { + code: ` +class Foo {} +class CustomError extends Foo {} +throw new CustomError(); + `, + errors: [ + { + messageId: 'object', + }, + ], + }, + { + code: ` +const Error = null; +throw Error; + `, + errors: [ + { + messageId: 'object', + }, + ], + }, + ], +});