2 * @fileoverview Ensure handling of errors when we know they exist.
3 * @author Jamund Ferguson
8 //------------------------------------------------------------------------------
10 //------------------------------------------------------------------------------
21 description: "require error handling in callbacks",
22 category: "Node.js and CommonJS",
24 url: "https://eslint.org/docs/rules/handle-callback-err"
33 expected: "Expected error to be handled."
39 const errorArgument = context.options[0] || "err";
42 * Checks if the given argument should be interpreted as a regexp pattern.
43 * @param {string} stringToCheck The string which should be checked.
44 * @returns {boolean} Whether or not the string should be interpreted as a pattern.
46 function isPattern(stringToCheck) {
47 const firstChar = stringToCheck[0];
49 return firstChar === "^";
53 * Checks if the given name matches the configured error argument.
54 * @param {string} name The name which should be compared.
55 * @returns {boolean} Whether or not the given name matches the configured error variable name.
57 function matchesConfiguredErrorName(name) {
58 if (isPattern(errorArgument)) {
59 const regexp = new RegExp(errorArgument, "u");
61 return regexp.test(name);
63 return name === errorArgument;
67 * Get the parameters of a given function scope.
68 * @param {Object} scope The function scope.
69 * @returns {Array} All parameters of the given scope.
71 function getParameters(scope) {
72 return scope.variables.filter(variable => variable.defs[0] && variable.defs[0].type === "Parameter");
76 * Check to see if we're handling the error object properly.
77 * @param {ASTNode} node The AST node to check.
80 function checkForError(node) {
81 const scope = context.getScope(),
82 parameters = getParameters(scope),
83 firstParameter = parameters[0];
85 if (firstParameter && matchesConfiguredErrorName(firstParameter.name)) {
86 if (firstParameter.references.length === 0) {
87 context.report({ node, messageId: "expected" });
93 FunctionDeclaration: checkForError,
94 FunctionExpression: checkForError,
95 ArrowFunctionExpression: checkForError