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