throw-new-error.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. 'use strict';
  2. const {matches} = require('./selectors/index.js');
  3. const {switchCallExpressionToNewExpression} = require('./fix/index.js');
  4. const messageId = 'throw-new-error';
  5. const messages = {
  6. [messageId]: 'Use `new` when throwing an error.',
  7. };
  8. const customError = /^(?:[A-Z][\da-z]*)*Error$/;
  9. const selector = [
  10. 'ThrowStatement',
  11. ' > ',
  12. 'CallExpression.argument',
  13. matches([
  14. // `throw FooError()`
  15. [
  16. '[callee.type="Identifier"]',
  17. `[callee.name=/${customError.source}/]`,
  18. ].join(''),
  19. // `throw lib.FooError()`
  20. [
  21. '[callee.type="MemberExpression"]',
  22. '[callee.computed!=true]',
  23. '[callee.property.type="Identifier"]',
  24. `[callee.property.name=/${customError.source}/]`,
  25. ].join(''),
  26. ]),
  27. ].join('');
  28. /** @param {import('eslint').Rule.RuleContext} context */
  29. const create = context => ({
  30. [selector]: node => ({
  31. node,
  32. messageId,
  33. fix: fixer => switchCallExpressionToNewExpression(node, context.getSourceCode(), fixer),
  34. }),
  35. });
  36. /** @type {import('eslint').Rule.RuleModule} */
  37. module.exports = {
  38. create,
  39. meta: {
  40. type: 'suggestion',
  41. docs: {
  42. description: 'Require `new` when throwing an error.',
  43. },
  44. fixable: 'code',
  45. messages,
  46. },
  47. };