validator.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /*!
  2. * Module dependencies.
  3. */
  4. var MongooseError = require('../error.js');
  5. var errorMessages = MongooseError.messages;
  6. /**
  7. * Schema validator error
  8. *
  9. * @param {Object} properties
  10. * @inherits MongooseError
  11. * @api private
  12. */
  13. function ValidatorError (properties) {
  14. var msg = properties.message;
  15. if (!msg) {
  16. msg = errorMessages.general.default;
  17. }
  18. this.properties = properties;
  19. var message = this.formatMessage(msg, properties);
  20. MongooseError.call(this, message);
  21. this.stack = new Error().stack;
  22. this.name = 'ValidatorError';
  23. this.kind = properties.type;
  24. this.path = properties.path;
  25. this.value = properties.value;
  26. };
  27. /*!
  28. * Inherits from MongooseError
  29. */
  30. ValidatorError.prototype = Object.create(MongooseError.prototype);
  31. ValidatorError.prototype.constructor = MongooseError;
  32. /*!
  33. * Formats error messages
  34. */
  35. ValidatorError.prototype.formatMessage = function (msg, properties) {
  36. var propertyNames = Object.keys(properties);
  37. for (var i = 0; i < propertyNames.length; ++i) {
  38. var propertyName = propertyNames[i];
  39. if (propertyName === 'message') {
  40. continue;
  41. }
  42. msg = msg.replace('{' + propertyName.toUpperCase() + '}', properties[propertyName]);
  43. }
  44. return msg;
  45. };
  46. /*!
  47. * toString helper
  48. */
  49. ValidatorError.prototype.toString = function () {
  50. return this.message;
  51. }
  52. /*!
  53. * exports
  54. */
  55. module.exports = ValidatorError;