index.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. /*!
  2. * assertion-error
  3. * Copyright(c) 2013 Jake Luer <jake@qualiancy.com>
  4. * MIT Licensed
  5. */
  6. /*!
  7. * Return a function that will copy properties from
  8. * one object to another excluding any originally
  9. * listed. Returned function will create a new `{}`.
  10. *
  11. * @param {String} excluded properties ...
  12. * @return {Function}
  13. */
  14. function exclude () {
  15. var excludes = [].slice.call(arguments);
  16. function excludeProps (res, obj) {
  17. Object.keys(obj).forEach(function (key) {
  18. if (!~excludes.indexOf(key)) res[key] = obj[key];
  19. });
  20. }
  21. return function extendExclude () {
  22. var args = [].slice.call(arguments)
  23. , i = 0
  24. , res = {};
  25. for (; i < args.length; i++) {
  26. excludeProps(res, args[i]);
  27. }
  28. return res;
  29. };
  30. };
  31. /*!
  32. * Primary Exports
  33. */
  34. module.exports = AssertionError;
  35. /**
  36. * ### AssertionError
  37. *
  38. * An extension of the JavaScript `Error` constructor for
  39. * assertion and validation scenarios.
  40. *
  41. * @param {String} message
  42. * @param {Object} properties to include (optional)
  43. * @param {callee} start stack function (optional)
  44. */
  45. function AssertionError (message, _props, ssf) {
  46. var extend = exclude('name', 'message', 'stack', 'constructor', 'toJSON')
  47. , props = extend(_props || {});
  48. // default values
  49. this.message = message || 'Unspecified AssertionError';
  50. this.showDiff = false;
  51. // copy from properties
  52. for (var key in props) {
  53. this[key] = props[key];
  54. }
  55. // capture stack trace
  56. ssf = ssf || arguments.callee;
  57. if (ssf && Error.captureStackTrace) {
  58. Error.captureStackTrace(this, ssf);
  59. }
  60. }
  61. /*!
  62. * Inherit from Error.prototype
  63. */
  64. AssertionError.prototype = Object.create(Error.prototype);
  65. /*!
  66. * Statically set name
  67. */
  68. AssertionError.prototype.name = 'AssertionError';
  69. /*!
  70. * Ensure correct constructor
  71. */
  72. AssertionError.prototype.constructor = AssertionError;
  73. /**
  74. * Allow errors to be converted to JSON for static transfer.
  75. *
  76. * @param {Boolean} include stack (default: `true`)
  77. * @return {Object} object that can be `JSON.stringify`
  78. */
  79. AssertionError.prototype.toJSON = function (stack) {
  80. var extend = exclude('constructor', 'toJSON', 'stack')
  81. , props = extend({ name: this.name }, this);
  82. // include stack if exists and not turned off
  83. if (false !== stack && this.stack) {
  84. props.stack = this.stack;
  85. }
  86. return props;
  87. };