no-useless-catch.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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. module.exports = {
  10. meta: {
  11. type: "suggestion",
  12. docs: {
  13. description: "disallow unnecessary `catch` clauses",
  14. category: "Best Practices",
  15. recommended: true,
  16. url: "https://eslint.org/docs/rules/no-useless-catch"
  17. },
  18. schema: []
  19. },
  20. create(context) {
  21. return {
  22. CatchClause(node) {
  23. if (
  24. node.param &&
  25. node.param.type === "Identifier" &&
  26. node.body.body.length &&
  27. node.body.body[0].type === "ThrowStatement" &&
  28. node.body.body[0].argument.type === "Identifier" &&
  29. node.body.body[0].argument.name === node.param.name
  30. ) {
  31. if (node.parent.finalizer) {
  32. context.report({
  33. node,
  34. message: "Unnecessary catch clause."
  35. });
  36. } else {
  37. context.report({
  38. node: node.parent,
  39. message: "Unnecessary try/catch wrapper."
  40. });
  41. }
  42. }
  43. }
  44. };
  45. }
  46. };