no-throw-literal.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /**
  2. * @fileoverview Rule to restrict what can be thrown as an exception.
  3. * @author Dieter Oberkofler
  4. */
  5. "use strict";
  6. const astUtils = require("./utils/ast-utils");
  7. //------------------------------------------------------------------------------
  8. // Rule Definition
  9. //------------------------------------------------------------------------------
  10. module.exports = {
  11. meta: {
  12. type: "suggestion",
  13. docs: {
  14. description: "disallow throwing literals as exceptions",
  15. category: "Best Practices",
  16. recommended: false,
  17. url: "https://eslint.org/docs/rules/no-throw-literal"
  18. },
  19. schema: [],
  20. messages: {
  21. object: "Expected an error object to be thrown.",
  22. undef: "Do not throw undefined."
  23. }
  24. },
  25. create(context) {
  26. return {
  27. ThrowStatement(node) {
  28. if (!astUtils.couldBeError(node.argument)) {
  29. context.report({ node, messageId: "object" });
  30. } else if (node.argument.type === "Identifier") {
  31. if (node.argument.name === "undefined") {
  32. context.report({ node, messageId: "undef" });
  33. }
  34. }
  35. }
  36. };
  37. }
  38. };