AbstractMethodError.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Ivan Kopeykin @vankop
  4. */
  5. "use strict";
  6. const WebpackError = require("./WebpackError");
  7. const CURRENT_METHOD_REGEXP = /at ([a-zA-Z0-9_.]*)/;
  8. /**
  9. * Creates the error message shown when an abstract API is called without
  10. * being implemented by a subclass.
  11. * @param {string=} method method name
  12. * @returns {string} message
  13. */
  14. function createMessage(method) {
  15. return `Abstract method${method ? ` ${method}` : ""}. Must be overridden.`;
  16. }
  17. /**
  18. * Captures a stack trace so the calling method name can be folded into the
  19. * final abstract-method error message.
  20. * @constructor
  21. */
  22. function Message() {
  23. /** @type {string | undefined} */
  24. this.stack = undefined;
  25. Error.captureStackTrace(this);
  26. /** @type {RegExpMatchArray | null} */
  27. const match =
  28. /** @type {string} */
  29. (/** @type {unknown} */ (this.stack))
  30. .split("\n")[3]
  31. .match(CURRENT_METHOD_REGEXP);
  32. this.message = match && match[1] ? createMessage(match[1]) : createMessage();
  33. }
  34. /**
  35. * Error thrown when code reaches a method that is intended to be overridden by
  36. * a subclass.
  37. * @example
  38. * ```js
  39. * class FooClass {
  40. * abstractMethod() {
  41. * throw new AbstractMethodError(); // error message: Abstract method FooClass.abstractMethod. Must be overridden.
  42. * }
  43. * }
  44. * ```
  45. */
  46. class AbstractMethodError extends WebpackError {
  47. /**
  48. * Creates an error whose message points at the abstract method that was
  49. * invoked.
  50. */
  51. constructor() {
  52. super(new Message().message);
  53. /** @type {string} */
  54. this.name = "AbstractMethodError";
  55. }
  56. }
  57. module.exports = AbstractMethodError;