trace.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. // Inspired by https://github.com/tlrobinson/long-stack-traces
  2. var EventEmitter = require('events').EventEmitter;
  3. var util = require('util');
  4. function extendTrace(object, property, pos) {
  5. var old = object[property];
  6. object[property] = function() {
  7. var error = new Error();
  8. var name = object.constructor.name + '#' + property + '(' +
  9. Array.prototype.slice.call(arguments).map(function(el) {
  10. return util.inspect(el, false, 0);
  11. }).join(', ') + ')';
  12. if (typeof pos === 'undefined') pos = -1;
  13. if (pos < 0) pos += arguments.length;
  14. var cb = arguments[pos];
  15. if (typeof arguments[pos] === 'function') {
  16. arguments[pos] = function replacement() {
  17. try {
  18. return cb.apply(this, arguments);
  19. } catch (err) {
  20. if (err && err.stack && !err.__augmented) {
  21. err.stack = filter(err).join('\n');
  22. err.stack += '\n--> in ' + name;
  23. err.stack += '\n' + filter(error).slice(1).join('\n');
  24. err.__augmented = true;
  25. }
  26. throw err;
  27. }
  28. };
  29. }
  30. return old.apply(this, arguments);
  31. };
  32. }
  33. exports.extendTrace = extendTrace;
  34. function filter(error) {
  35. return error.stack.split('\n').filter(function(line) {
  36. return line.indexOf(__filename) < 0;
  37. });
  38. }