trace.js 1.3 KB

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