HookWebpackError.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Sean Larkin @thelarkinn
  4. */
  5. "use strict";
  6. const WebpackError = require("./WebpackError");
  7. /** @typedef {import("./Module")} Module */
  8. /**
  9. * @template T
  10. * @callback Callback
  11. * @param {Error | null} err
  12. * @param {T=} stats
  13. * @returns {void}
  14. */
  15. class HookWebpackError extends WebpackError {
  16. /**
  17. * Creates an instance of HookWebpackError.
  18. * @param {Error} error inner error
  19. * @param {string} hook name of hook
  20. */
  21. constructor(error, hook) {
  22. super(error.message);
  23. this.name = "HookWebpackError";
  24. this.hook = hook;
  25. this.error = error;
  26. this.hideStack = true;
  27. this.details = `caused by plugins in ${hook}\n${error.stack}`;
  28. this.stack += `\n-- inner error --\n${error.stack}`;
  29. }
  30. }
  31. module.exports = HookWebpackError;
  32. /**
  33. * @param {Error} error an error
  34. * @param {string} hook name of the hook
  35. * @returns {WebpackError} a webpack error
  36. */
  37. const makeWebpackError = (error, hook) => {
  38. if (error instanceof WebpackError) return error;
  39. return new HookWebpackError(error, hook);
  40. };
  41. module.exports.makeWebpackError = makeWebpackError;
  42. /**
  43. * @template T
  44. * @param {function(WebpackError | null, T=): void} callback webpack error callback
  45. * @param {string} hook name of hook
  46. * @returns {Callback<T>} generic callback
  47. */
  48. const makeWebpackErrorCallback = (callback, hook) => {
  49. return (err, result) => {
  50. if (err) {
  51. if (err instanceof WebpackError) {
  52. callback(err);
  53. return;
  54. }
  55. callback(new HookWebpackError(err, hook));
  56. return;
  57. }
  58. callback(null, result);
  59. };
  60. };
  61. module.exports.makeWebpackErrorCallback = makeWebpackErrorCallback;
  62. /**
  63. * @template T
  64. * @param {function(): T} fn function which will be wrapping in try catch
  65. * @param {string} hook name of hook
  66. * @returns {T} the result
  67. */
  68. const tryRunOrWebpackError = (fn, hook) => {
  69. let r;
  70. try {
  71. r = fn();
  72. } catch (err) {
  73. if (err instanceof WebpackError) {
  74. throw err;
  75. }
  76. throw new HookWebpackError(/** @type {Error} */ (err), hook);
  77. }
  78. return r;
  79. };
  80. module.exports.tryRunOrWebpackError = tryRunOrWebpackError;