handle-callback-err.js 2.9 KB

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