UNPKG

2.89 kBJavaScriptView Raw
1/**
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 docs: {
15 description: "require error handling in callbacks",
16 category: "Node.js and CommonJS",
17 recommended: false,
18 url: "https://eslint.org/docs/rules/handle-callback-err"
19 },
20
21 schema: [
22 {
23 type: "string"
24 }
25 ]
26 },
27
28 create(context) {
29
30 const errorArgument = context.options[0] || "err";
31
32 /**
33 * Checks if the given argument should be interpreted as a regexp pattern.
34 * @param {string} stringToCheck The string which should be checked.
35 * @returns {boolean} Whether or not the string should be interpreted as a pattern.
36 */
37 function isPattern(stringToCheck) {
38 const firstChar = stringToCheck[0];
39
40 return firstChar === "^";
41 }
42
43 /**
44 * Checks if the given name matches the configured error argument.
45 * @param {string} name The name which should be compared.
46 * @returns {boolean} Whether or not the given name matches the configured error variable name.
47 */
48 function matchesConfiguredErrorName(name) {
49 if (isPattern(errorArgument)) {
50 const regexp = new RegExp(errorArgument);
51
52 return regexp.test(name);
53 }
54 return name === errorArgument;
55 }
56
57 /**
58 * Get the parameters of a given function scope.
59 * @param {Object} scope The function scope.
60 * @returns {array} All parameters of the given scope.
61 */
62 function getParameters(scope) {
63 return scope.variables.filter(variable => variable.defs[0] && variable.defs[0].type === "Parameter");
64 }
65
66 /**
67 * Check to see if we're handling the error object properly.
68 * @param {ASTNode} node The AST node to check.
69 * @returns {void}
70 */
71 function checkForError(node) {
72 const scope = context.getScope(),
73 parameters = getParameters(scope),
74 firstParameter = parameters[0];
75
76 if (firstParameter && matchesConfiguredErrorName(firstParameter.name)) {
77 if (firstParameter.references.length === 0) {
78 context.report({ node, message: "Expected error to be handled." });
79 }
80 }
81 }
82
83 return {
84 FunctionDeclaration: checkForError,
85 FunctionExpression: checkForError,
86 ArrowFunctionExpression: checkForError
87 };
88
89 }
90};