|
| 1 | +/* |
| 2 | + * eslint-plugin-sonarjs |
| 3 | + * Copyright (C) 2018 SonarSource SA |
| 4 | + * mailto:info AT sonarsource DOT com |
| 5 | + * |
| 6 | + * This program is free software; you can redistribute it and/or |
| 7 | + * modify it under the terms of the GNU Lesser General Public |
| 8 | + * License as published by the Free Software Foundation; either |
| 9 | + * version 3 of the License, or (at your option) any later version. |
| 10 | + * |
| 11 | + * This program is distributed in the hope that it will be useful, |
| 12 | + * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 13 | + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
| 14 | + * Lesser General Public License for more details. |
| 15 | + * |
| 16 | + * You should have received a copy of the GNU Lesser General Public License |
| 17 | + * along with this program; if not, write to the Free Software Foundation, |
| 18 | + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. |
| 19 | + */ |
| 20 | +// https://jira.sonarsource.com/browse/RSPEC-1940 |
| 21 | + |
| 22 | +import { Rule, SourceCode } from "eslint"; |
| 23 | +import { Node, CatchClause, Statement, Pattern } from "estree"; |
| 24 | +import { isThrowStatement } from "../utils/nodes"; |
| 25 | +import { areEquivalent } from "../utils/equivalence"; |
| 26 | + |
| 27 | +const MESSAGE = "Add logic to this catch clause or eliminate it and rethrow the exception automatically."; |
| 28 | + |
| 29 | +const rule: Rule.RuleModule = { |
| 30 | + create(context: Rule.RuleContext) { |
| 31 | + return { CatchClause: (node: Node) => visitCatchClause(node as CatchClause, context) }; |
| 32 | + }, |
| 33 | +}; |
| 34 | + |
| 35 | +function visitCatchClause(catchClause: CatchClause, context: Rule.RuleContext) { |
| 36 | + const statements = catchClause.body.body; |
| 37 | + if (statements.length === 1 && onlyRethrows(statements[0], catchClause.param, context.getSourceCode())) { |
| 38 | + const catchKeyword = context.getSourceCode().getFirstToken(catchClause); |
| 39 | + context.report({ |
| 40 | + message: MESSAGE, |
| 41 | + loc: catchKeyword!.loc, |
| 42 | + }); |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +function onlyRethrows(statement: Statement, catchParam: Pattern, sourceCode: SourceCode) { |
| 47 | + return isThrowStatement(statement) && areEquivalent(catchParam, statement.argument, sourceCode); |
| 48 | +} |
| 49 | + |
| 50 | +export = rule; |
0 commit comments