validator.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /*!
  2. * Module dependencies.
  3. */
  4. 'use strict';
  5. const MongooseError = require('./');
  6. class ValidatorError extends MongooseError {
  7. /**
  8. * Schema validator error
  9. *
  10. * @param {Object} properties
  11. * @api private
  12. */
  13. constructor(properties) {
  14. let msg = properties.message;
  15. if (!msg) {
  16. msg = MongooseError.messages.general.default;
  17. }
  18. const message = formatMessage(msg, properties);
  19. super(message);
  20. properties = Object.assign({}, properties, { message: message });
  21. this.properties = properties;
  22. this.kind = properties.type;
  23. this.path = properties.path;
  24. this.value = properties.value;
  25. this.reason = properties.reason;
  26. }
  27. /*!
  28. * toString helper
  29. * TODO remove? This defaults to `${this.name}: ${this.message}`
  30. */
  31. toString() {
  32. return this.message;
  33. }
  34. }
  35. Object.defineProperty(ValidatorError.prototype, 'name', {
  36. value: 'ValidatorError'
  37. });
  38. /*!
  39. * The object used to define this validator. Not enumerable to hide
  40. * it from `require('util').inspect()` output re: gh-3925
  41. */
  42. Object.defineProperty(ValidatorError.prototype, 'properties', {
  43. enumerable: false,
  44. writable: true,
  45. value: null
  46. });
  47. // Exposed for testing
  48. ValidatorError.prototype.formatMessage = formatMessage;
  49. /*!
  50. * Formats error messages
  51. */
  52. function formatMessage(msg, properties) {
  53. if (typeof msg === 'function') {
  54. return msg(properties);
  55. }
  56. const propertyNames = Object.keys(properties);
  57. for (const propertyName of propertyNames) {
  58. if (propertyName === 'message') {
  59. continue;
  60. }
  61. msg = msg.replace('{' + propertyName.toUpperCase() + '}', properties[propertyName]);
  62. }
  63. return msg;
  64. }
  65. /*!
  66. * exports
  67. */
  68. module.exports = ValidatorError;