UNPKG

2.85 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 },
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(function(variable) {
63 return variable.defs[0] && variable.defs[0].type === "Parameter";
64 });
65 }
66
67 /**
68 * Check to see if we're handling the error object properly.
69 * @param {ASTNode} node The AST node to check.
70 * @returns {void}
71 */
72 function checkForError(node) {
73 const scope = context.getScope(),
74 parameters = getParameters(scope),
75 firstParameter = parameters[0];
76
77 if (firstParameter && matchesConfiguredErrorName(firstParameter.name)) {
78 if (firstParameter.references.length === 0) {
79 context.report(node, "Expected error to be handled.");
80 }
81 }
82 }
83
84 return {
85 FunctionDeclaration: checkForError,
86 FunctionExpression: checkForError,
87 ArrowFunctionExpression: checkForError
88 };
89
90 }
91};