no-useless-catch.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. "use strict";
  2. /*
  3. * eslint-plugin-sonarjs
  4. * Copyright (C) 2018-2021 SonarSource SA
  5. * mailto:info AT sonarsource DOT com
  6. *
  7. * This program is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 3 of the License, or (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public License
  18. * along with this program; if not, write to the Free Software Foundation,
  19. * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  20. */
  21. // https://sonarsource.github.io/rspec/#/rspec/S1940
  22. const nodes_1 = require("../utils/nodes");
  23. const equivalence_1 = require("../utils/equivalence");
  24. const docs_url_1 = require("../utils/docs-url");
  25. const rule = {
  26. meta: {
  27. messages: {
  28. uselessCatch: 'Add logic to this catch clause or eliminate it and rethrow the exception automatically.',
  29. },
  30. schema: [],
  31. type: 'suggestion',
  32. docs: {
  33. description: '"catch" clauses should do more than rethrow',
  34. recommended: 'error',
  35. url: (0, docs_url_1.default)(__filename),
  36. },
  37. },
  38. create(context) {
  39. return {
  40. CatchClause: (node) => visitCatchClause(node, context),
  41. };
  42. },
  43. };
  44. function visitCatchClause(catchClause, context) {
  45. const statements = catchClause.body.body;
  46. if (catchClause.param &&
  47. statements.length === 1 &&
  48. onlyRethrows(statements[0], catchClause.param, context.getSourceCode())) {
  49. const catchKeyword = context.getSourceCode().getFirstToken(catchClause);
  50. context.report({
  51. messageId: 'uselessCatch',
  52. loc: catchKeyword.loc,
  53. });
  54. }
  55. }
  56. function onlyRethrows(statement, catchParam, sourceCode) {
  57. return ((0, nodes_1.isThrowStatement)(statement) &&
  58. catchParam !== null &&
  59. statement.argument !== null &&
  60. (0, equivalence_1.areEquivalent)(catchParam, statement.argument, sourceCode));
  61. }
  62. module.exports = rule;
  63. //# sourceMappingURL=no-useless-catch.js.map