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