no-useless-catch.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /**
  2. * @fileoverview Reports useless `catch` clauses that just rethrow their error.
  3. * @author Teddy Katz
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Rule Definition
  8. //------------------------------------------------------------------------------
  9. /** @type {import('../shared/types').Rule} */
  10. module.exports = {
  11. meta: {
  12. type: "suggestion",
  13. docs: {
  14. description: "Disallow unnecessary `catch` clauses",
  15. recommended: true,
  16. url: "https://eslint.org/docs/rules/no-useless-catch"
  17. },
  18. schema: [],
  19. messages: {
  20. unnecessaryCatchClause: "Unnecessary catch clause.",
  21. unnecessaryCatch: "Unnecessary try/catch wrapper."
  22. }
  23. },
  24. create(context) {
  25. return {
  26. CatchClause(node) {
  27. if (
  28. node.param &&
  29. node.param.type === "Identifier" &&
  30. node.body.body.length &&
  31. node.body.body[0].type === "ThrowStatement" &&
  32. node.body.body[0].argument.type === "Identifier" &&
  33. node.body.body[0].argument.name === node.param.name
  34. ) {
  35. if (node.parent.finalizer) {
  36. context.report({
  37. node,
  38. messageId: "unnecessaryCatchClause"
  39. });
  40. } else {
  41. context.report({
  42. node: node.parent,
  43. messageId: "unnecessaryCatch"
  44. });
  45. }
  46. }
  47. }
  48. };
  49. }
  50. };