consolidate-errors.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /**
  2. * Module dependencies
  3. */
  4. var util = require('util');
  5. var _ = require('@sailshq/lodash');
  6. /**
  7. * Combine an array of errors into a single Error object.
  8. *
  9. * @param {Array} errors
  10. * @param {String} msgSuffix
  11. * @return {Error}
  12. */
  13. module.exports = function consolidateErrors (errors, msgSuffix) {
  14. // If there are errors, coallesce them into a single Error object we can throw.
  15. if (errors.length === 0) {
  16. return;
  17. }
  18. // Remove duplicate E_NOT_EVEN_CLOSE / E_NOT_STRICTLY_VALID errors.
  19. var uniqueErrors = _.uniq(errors, function disregardValidationErrCode(err){
  20. var hash = '';
  21. if (!err.code) {
  22. hash += '?';
  23. }
  24. else if (err.code !== 'E_NOT_EVEN_CLOSE' && err.code !== 'E_NOT_STRICTLY_VALID') {
  25. hash += err.code;
  26. }
  27. hash += err.expected;
  28. if (err.hops) {
  29. hash += err.hops.join('.');
  30. }
  31. return hash;
  32. });
  33. var errMsg = util.format(
  34. '%d error%s%s:',
  35. uniqueErrors.length, (uniqueErrors.length!==1?'s':''), (msgSuffix?(' '+msgSuffix):''),
  36. (
  37. '\n • '+ _.pluck(uniqueErrors, 'message').join('\n • ')
  38. )
  39. );
  40. var err = new Error(errMsg);
  41. // Determine the appropriate top-level error code.
  42. if (_.any(uniqueErrors, { code: 'E_UNKNOWN_TYPE' })) {
  43. err.code = 'E_UNKNOWN_TYPE';
  44. }
  45. else {
  46. err.code = 'E_INVALID';
  47. }
  48. // If any of the original errors are not "minor", then this is not a "minor" error.
  49. err.minor = _.reduce(errors, function(memo, subError) {
  50. if (!memo || !subError.minor) {
  51. return false;
  52. }
  53. return true;
  54. }, true);
  55. // Don't include `minor` property if it's falsy.
  56. if (!err.minor) {
  57. delete err.minor;
  58. }
  59. // Expose duplicate-free list of errors as `err.errors`
  60. err.errors = uniqueErrors;
  61. return err;
  62. };