index.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. 'use strict';
  2. const indentString = require('indent-string');
  3. const cleanStack = require('clean-stack');
  4. const cleanInternalStack = stack => stack.replace(/\s+at .*aggregate-error\/index.js:\d+:\d+\)?/g, '');
  5. class AggregateError extends Error {
  6. constructor(errors) {
  7. if (!Array.isArray(errors)) {
  8. throw new TypeError(`Expected input to be an Array, got ${typeof errors}`);
  9. }
  10. errors = [...errors].map(error => {
  11. if (error instanceof Error) {
  12. return error;
  13. }
  14. if (error !== null && typeof error === 'object') {
  15. // Handle plain error objects with message property and/or possibly other metadata
  16. return Object.assign(new Error(error.message), error);
  17. }
  18. return new Error(error);
  19. });
  20. let message = errors
  21. .map(error => {
  22. // The `stack` property is not standardized, so we can't assume it exists
  23. return typeof error.stack === 'string' ? cleanInternalStack(cleanStack(error.stack)) : String(error);
  24. })
  25. .join('\n');
  26. message = '\n' + indentString(message, 4);
  27. super(message);
  28. this.name = 'AggregateError';
  29. Object.defineProperty(this, '_errors', {value: errors});
  30. }
  31. * [Symbol.iterator]() {
  32. for (const error of this._errors) {
  33. yield error;
  34. }
  35. }
  36. }
  37. module.exports = AggregateError;