index.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. 'use strict';
  2. var util = require('util');
  3. var isArrayish = require('is-arrayish');
  4. var errorEx = function errorEx(name, properties) {
  5. if (!name || name.constructor !== String) {
  6. properties = name || {};
  7. name = Error.name;
  8. }
  9. var errorExError = function ErrorEXError(message) {
  10. if (!this) {
  11. return new ErrorEXError(message);
  12. }
  13. message = message instanceof Error
  14. ? message.message
  15. : (message || this.message);
  16. Error.call(this, message);
  17. Error.captureStackTrace(this, errorExError);
  18. this.name = name;
  19. delete this.message;
  20. Object.defineProperty(this, 'message', {
  21. configurable: true,
  22. enumerable: false,
  23. get: function () {
  24. var newMessage = message.split(/\r?\n/g);
  25. for (var key in properties) {
  26. if (properties.hasOwnProperty(key) && 'message' in properties[key]) {
  27. newMessage = properties[key].message(this[key], newMessage) ||
  28. newMessage;
  29. if (!isArrayish(newMessage)) {
  30. newMessage = [newMessage];
  31. }
  32. }
  33. }
  34. return newMessage.join('\n');
  35. },
  36. set: function (v) {
  37. message = v;
  38. }
  39. });
  40. var stackDescriptor = Object.getOwnPropertyDescriptor(this, 'stack');
  41. var stackGetter = stackDescriptor.get;
  42. stackDescriptor.get = function () {
  43. var stack = stackGetter.call(this).split(/\r?\n+/g);
  44. var lineCount = 1;
  45. for (var key in properties) {
  46. if (!properties.hasOwnProperty(key)) {
  47. continue;
  48. }
  49. var modifier = properties[key];
  50. if ('line' in modifier) {
  51. var line = modifier.line(this[key]);
  52. if (line) {
  53. stack.splice(lineCount, 0, ' ' + line);
  54. }
  55. }
  56. if ('stack' in modifier) {
  57. modifier.stack(this[key], stack);
  58. }
  59. }
  60. return stack.join('\n');
  61. };
  62. Object.defineProperty(this, 'stack', stackDescriptor);
  63. };
  64. util.inherits(errorExError, Error);
  65. return errorExError;
  66. };
  67. errorEx.append = function (str, def) {
  68. return {
  69. message: function (v, message) {
  70. v = v || def;
  71. if (v) {
  72. message[0] += ' ' + str.replace('%s', v.toString());
  73. }
  74. return message;
  75. }
  76. };
  77. };
  78. errorEx.line = function (str, def) {
  79. return {
  80. line: function (v) {
  81. v = v || def;
  82. if (v) {
  83. return str.replace('%s', v.toString());
  84. }
  85. return null;
  86. }
  87. };
  88. };
  89. module.exports = errorEx;