handle-callback-err.js 2.9 KB

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