cast.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. 'use strict';
  2. /*!
  3. * Module dependencies.
  4. */
  5. const MongooseError = require('./mongooseError');
  6. const util = require('util');
  7. /**
  8. * Casting Error constructor.
  9. *
  10. * @param {String} type
  11. * @param {String} value
  12. * @inherits MongooseError
  13. * @api private
  14. */
  15. function CastError(type, value, path, reason) {
  16. let stringValue = util.inspect(value);
  17. stringValue = stringValue.replace(/^'/, '"').replace(/'$/, '"');
  18. if (stringValue.charAt(0) !== '"') {
  19. stringValue = '"' + stringValue + '"';
  20. }
  21. MongooseError.call(this, 'Cast to ' + type + ' failed for value ' +
  22. stringValue + ' at path "' + path + '"');
  23. this.name = 'CastError';
  24. if (Error.captureStackTrace) {
  25. Error.captureStackTrace(this);
  26. } else {
  27. this.stack = new Error().stack;
  28. }
  29. this.stringValue = stringValue;
  30. this.kind = type;
  31. this.value = value;
  32. this.path = path;
  33. this.reason = reason;
  34. }
  35. /*!
  36. * Inherits from MongooseError.
  37. */
  38. CastError.prototype = Object.create(MongooseError.prototype);
  39. CastError.prototype.constructor = MongooseError;
  40. /*!
  41. * ignore
  42. */
  43. CastError.prototype.setModel = function(model) {
  44. this.model = model;
  45. this.message = 'Cast to ' + this.kind + ' failed for value ' +
  46. this.stringValue + ' at path "' + this.path + '"' + ' for model "' +
  47. model.modelName + '"';
  48. };
  49. /*!
  50. * exports
  51. */
  52. module.exports = CastError;