validation.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. /*!
  2. * Module requirements
  3. */
  4. 'use strict';
  5. const MongooseError = require('./');
  6. const util = require('util');
  7. /**
  8. * Document Validation Error
  9. *
  10. * @api private
  11. * @param {Document} instance
  12. * @inherits MongooseError
  13. */
  14. function ValidationError(instance) {
  15. this.errors = {};
  16. this._message = '';
  17. if (instance && instance.constructor.name === 'model') {
  18. this._message = instance.constructor.modelName + ' validation failed';
  19. MongooseError.call(this, this._message);
  20. } else {
  21. this._message = 'Validation failed';
  22. MongooseError.call(this, this._message);
  23. }
  24. this.name = 'ValidationError';
  25. if (Error.captureStackTrace) {
  26. Error.captureStackTrace(this);
  27. } else {
  28. this.stack = new Error().stack;
  29. }
  30. if (instance) {
  31. instance.errors = this.errors;
  32. }
  33. }
  34. /*!
  35. * Inherits from MongooseError.
  36. */
  37. ValidationError.prototype = Object.create(MongooseError.prototype);
  38. ValidationError.prototype.constructor = MongooseError;
  39. /**
  40. * Console.log helper
  41. */
  42. ValidationError.prototype.toString = function() {
  43. return this.name + ': ' + _generateMessage(this);
  44. };
  45. /*!
  46. * inspect helper
  47. */
  48. ValidationError.prototype.inspect = function() {
  49. return Object.assign(new Error(this.message), this);
  50. };
  51. if (util.inspect.custom) {
  52. /*!
  53. * Avoid Node deprecation warning DEP0079
  54. */
  55. ValidationError.prototype[util.inspect.custom] = ValidationError.prototype.inspect;
  56. }
  57. /*!
  58. * Helper for JSON.stringify
  59. */
  60. ValidationError.prototype.toJSON = function() {
  61. return Object.assign({}, this, { message: this.message });
  62. };
  63. /*!
  64. * add message
  65. */
  66. ValidationError.prototype.addError = function(path, error) {
  67. this.errors[path] = error;
  68. this.message = this._message + ': ' + _generateMessage(this);
  69. };
  70. /*!
  71. * ignore
  72. */
  73. function _generateMessage(err) {
  74. const keys = Object.keys(err.errors || {});
  75. const len = keys.length;
  76. const msgs = [];
  77. let key;
  78. for (let i = 0; i < len; ++i) {
  79. key = keys[i];
  80. if (err === err.errors[key]) {
  81. continue;
  82. }
  83. msgs.push(key + ': ' + err.errors[key].message);
  84. }
  85. return msgs.join(', ');
  86. }
  87. /*!
  88. * Module exports
  89. */
  90. module.exports = exports = ValidationError;