2 * @fileoverview Ensure handling of errors when we know they exist.
3 * @author Jamund Ferguson
8 //------------------------------------------------------------------------------
10 //------------------------------------------------------------------------------
17 description: "require error handling in callbacks",
18 category: "Node.js and CommonJS",
20 url: "https://eslint.org/docs/rules/handle-callback-err"
29 expected: "Expected error to be handled."
35 const errorArgument = context.options[0] || "err";
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.
42 function isPattern(stringToCheck) {
43 const firstChar = stringToCheck[0];
45 return firstChar === "^";
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.
53 function matchesConfiguredErrorName(name) {
54 if (isPattern(errorArgument)) {
55 const regexp = new RegExp(errorArgument, "u");
57 return regexp.test(name);
59 return name === errorArgument;
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.
67 function getParameters(scope) {
68 return scope.variables.filter(variable => variable.defs[0] && variable.defs[0].type === "Parameter");
72 * Check to see if we're handling the error object properly.
73 * @param {ASTNode} node The AST node to check.
76 function checkForError(node) {
77 const scope = context.getScope(),
78 parameters = getParameters(scope),
79 firstParameter = parameters[0];
81 if (firstParameter && matchesConfiguredErrorName(firstParameter.name)) {
82 if (firstParameter.references.length === 0) {
83 context.report({ node, messageId: "expected" });
89 FunctionDeclaration: checkForError,
90 FunctionExpression: checkForError,
91 ArrowFunctionExpression: checkForError