validation.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. /*!
  2. * Module requirements
  3. */
  4. 'use strict';
  5. const MongooseError = require('./mongooseError');
  6. const getConstructorName = require('../helpers/getConstructorName');
  7. const util = require('util');
  8. const combinePathErrors = require('../helpers/error/combinePathErrors');
  9. /**
  10. * Document Validation Error
  11. *
  12. * @api private
  13. * @param {Document} [instance]
  14. * @inherits MongooseError
  15. */
  16. class ValidationError extends MongooseError {
  17. constructor(instance) {
  18. let _message;
  19. if (getConstructorName(instance) === 'model') {
  20. _message = instance.constructor.modelName + ' validation failed';
  21. } else {
  22. _message = 'Validation failed';
  23. }
  24. super(_message);
  25. this.errors = {};
  26. this._message = _message;
  27. if (instance) {
  28. instance.$errors = this.errors;
  29. }
  30. }
  31. /**
  32. * Console.log helper
  33. */
  34. toString() {
  35. return this.name + ': ' + combinePathErrors(this);
  36. }
  37. /**
  38. * add message
  39. * @param {String} path
  40. * @param {String|Error} error
  41. * @api private
  42. */
  43. addError(path, error) {
  44. if (error instanceof ValidationError) {
  45. const { errors } = error;
  46. for (const errorPath of Object.keys(errors)) {
  47. this.addError(`${path}.${errorPath}`, errors[errorPath]);
  48. }
  49. return;
  50. }
  51. this.errors[path] = error;
  52. this.message = this._message + ': ' + combinePathErrors(this);
  53. }
  54. }
  55. if (util.inspect.custom) {
  56. // Avoid Node deprecation warning DEP0079
  57. ValidationError.prototype[util.inspect.custom] = ValidationError.prototype.inspect;
  58. }
  59. /**
  60. * Helper for JSON.stringify
  61. * Ensure `name` and `message` show up in toJSON output re: gh-9847
  62. * @api private
  63. */
  64. Object.defineProperty(ValidationError.prototype, 'toJSON', {
  65. enumerable: false,
  66. writable: false,
  67. configurable: true,
  68. value: function() {
  69. return Object.assign({}, this, { name: this.name, message: this.message });
  70. }
  71. });
  72. Object.defineProperty(ValidationError.prototype, 'name', {
  73. value: 'ValidationError'
  74. });
  75. /*!
  76. * Module exports
  77. */
  78. module.exports = ValidationError;