-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
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
bradzacher
merged 6 commits into
typescript-eslint:master
from
a-tarasyuk:feature/no-throw-literal
Dec 20, 2019
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
9dc6da0
feat(eslint-plugin): add no-throw-literal
a-tarasyuk 9d892e5
feat(eslint-plugin): add no-throw-literal
a-tarasyuk 679bbb2
Merge branch 'master' of https://github.com/typescript-eslint/typescr…
a-tarasyuk 8e95494
fix(eslint-plugin): [no-throw-literal] fix spelling in docs
a-tarasyuk 9d743c0
Merge branch 'feature/no-throw-literal' of https://github.com/a-taras…
a-tarasyuk ec3223c
feat(eslint-plugin): [no-throw-literal] improve code coverage
a-tarasyuk File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
}, | ||
}; | ||
}, | ||
}); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.