handle-callback-err.js 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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: "https://github.com/weiran-zsd/eslint-plugin-node/blob/HEAD/docs/rules/handle-callback-err.md",
  14. },
  15. fixable: null,
  16. schema: [
  17. {
  18. type: "string",
  19. },
  20. ],
  21. messages: {
  22. expected: "Expected error to be handled.",
  23. },
  24. },
  25. create(context) {
  26. const errorArgument = context.options[0] || "err"
  27. /**
  28. * Checks if the given argument should be interpreted as a regexp pattern.
  29. * @param {string} stringToCheck The string which should be checked.
  30. * @returns {boolean} Whether or not the string should be interpreted as a pattern.
  31. */
  32. function isPattern(stringToCheck) {
  33. const firstChar = stringToCheck[0]
  34. return firstChar === "^"
  35. }
  36. /**
  37. * Checks if the given name matches the configured error argument.
  38. * @param {string} name The name which should be compared.
  39. * @returns {boolean} Whether or not the given name matches the configured error variable name.
  40. */
  41. function matchesConfiguredErrorName(name) {
  42. if (isPattern(errorArgument)) {
  43. const regexp = new RegExp(errorArgument, "u")
  44. return regexp.test(name)
  45. }
  46. return name === errorArgument
  47. }
  48. /**
  49. * Get the parameters of a given function scope.
  50. * @param {Object} scope The function scope.
  51. * @returns {Array} All parameters of the given scope.
  52. */
  53. function getParameters(scope) {
  54. return scope.variables.filter(
  55. variable =>
  56. variable.defs[0] && variable.defs[0].type === "Parameter"
  57. )
  58. }
  59. /**
  60. * Check to see if we're handling the error object properly.
  61. * @param {ASTNode} node The AST node to check.
  62. * @returns {void}
  63. */
  64. function checkForError(node) {
  65. const scope = context.getScope()
  66. const parameters = getParameters(scope)
  67. const firstParameter = parameters[0]
  68. if (
  69. firstParameter &&
  70. matchesConfiguredErrorName(firstParameter.name)
  71. ) {
  72. if (firstParameter.references.length === 0) {
  73. context.report({ node, messageId: "expected" })
  74. }
  75. }
  76. }
  77. return {
  78. FunctionDeclaration: checkForError,
  79. FunctionExpression: checkForError,
  80. ArrowFunctionExpression: checkForError,
  81. }
  82. },
  83. }