blob: 640946699e7bea3e0c9123c454e7109b95c4688d [file] [log] [blame]
Yang Guo4fd355c2019-09-19 10:59:03 +02001/**
2 * @fileoverview Ensure handling of errors when we know they exist.
3 * @author Jamund Ferguson
4 */
5
6"use strict";
7
8//------------------------------------------------------------------------------
9// Rule Definition
10//------------------------------------------------------------------------------
11
12module.exports = {
13 meta: {
14 type: "suggestion",
15
16 docs: {
17 description: "require error handling in callbacks",
18 category: "Node.js and CommonJS",
19 recommended: false,
20 url: "https://eslint.org/docs/rules/handle-callback-err"
21 },
22
23 schema: [
24 {
25 type: "string"
26 }
27 ],
28 messages: {
29 expected: "Expected error to be handled."
30 }
31 },
32
33 create(context) {
34
35 const errorArgument = context.options[0] || "err";
36
37 /**
38 * Checks if the given argument should be interpreted as a regexp pattern.
39 * @param {string} stringToCheck The string which should be checked.
40 * @returns {boolean} Whether or not the string should be interpreted as a pattern.
41 */
42 function isPattern(stringToCheck) {
43 const firstChar = stringToCheck[0];
44
45 return firstChar === "^";
46 }
47
48 /**
49 * Checks if the given name matches the configured error argument.
50 * @param {string} name The name which should be compared.
51 * @returns {boolean} Whether or not the given name matches the configured error variable name.
52 */
53 function matchesConfiguredErrorName(name) {
54 if (isPattern(errorArgument)) {
55 const regexp = new RegExp(errorArgument, "u");
56
57 return regexp.test(name);
58 }
59 return name === errorArgument;
60 }
61
62 /**
63 * Get the parameters of a given function scope.
64 * @param {Object} scope The function scope.
65 * @returns {Array} All parameters of the given scope.
66 */
67 function getParameters(scope) {
68 return scope.variables.filter(variable => variable.defs[0] && variable.defs[0].type === "Parameter");
69 }
70
71 /**
72 * Check to see if we're handling the error object properly.
73 * @param {ASTNode} node The AST node to check.
74 * @returns {void}
75 */
76 function checkForError(node) {
77 const scope = context.getScope(),
78 parameters = getParameters(scope),
79 firstParameter = parameters[0];
80
81 if (firstParameter && matchesConfiguredErrorName(firstParameter.name)) {
82 if (firstParameter.references.length === 0) {
83 context.report({ node, messageId: "expected" });
84 }
85 }
86 }
87
88 return {
89 FunctionDeclaration: checkForError,
90 FunctionExpression: checkForError,
91 ArrowFunctionExpression: checkForError
92 };
93
94 }
95};