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