SugaredTracer.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import { context, SpanStatusCode } from '../../';
  2. const defaultOnException = (e, span) => {
  3. span.recordException(e);
  4. span.setStatus({
  5. code: SpanStatusCode.ERROR,
  6. });
  7. };
  8. /**
  9. * return a new SugaredTracer created from the supplied one
  10. * @param tracer
  11. */
  12. export function wrapTracer(tracer) {
  13. return new SugaredTracer(tracer);
  14. }
  15. export class SugaredTracer {
  16. constructor(tracer) {
  17. this._tracer = tracer;
  18. this.startSpan = tracer.startSpan.bind(this._tracer);
  19. this.startActiveSpan = tracer.startActiveSpan.bind(this._tracer);
  20. }
  21. withActiveSpan(name, arg2, arg3, arg4) {
  22. const { opts, ctx, fn } = massageParams(arg2, arg3, arg4);
  23. return this._tracer.startActiveSpan(name, opts, ctx, (span) => handleFn(span, opts, fn));
  24. }
  25. withSpan(name, arg2, arg3, arg4) {
  26. const { opts, ctx, fn } = massageParams(arg2, arg3, arg4);
  27. const span = this._tracer.startSpan(name, opts, ctx);
  28. return handleFn(span, opts, fn);
  29. }
  30. }
  31. /**
  32. * Massages parameters of withSpan and withActiveSpan to allow signature overwrites
  33. * @param arg
  34. * @param arg2
  35. * @param arg3
  36. */
  37. function massageParams(arg, arg2, arg3) {
  38. let opts;
  39. let ctx;
  40. let fn;
  41. if (!arg2 && !arg3) {
  42. fn = arg;
  43. }
  44. else if (!arg3) {
  45. opts = arg;
  46. fn = arg2;
  47. }
  48. else {
  49. opts = arg;
  50. ctx = arg2;
  51. fn = arg3;
  52. }
  53. opts = opts !== null && opts !== void 0 ? opts : {};
  54. ctx = ctx !== null && ctx !== void 0 ? ctx : context.active();
  55. return { opts, ctx, fn };
  56. }
  57. /**
  58. * Executes fn, returns results and runs onException in the case of exception to allow overwriting of error handling
  59. * @param span
  60. * @param opts
  61. * @param fn
  62. */
  63. function handleFn(span, opts, fn) {
  64. var _a;
  65. const onException = (_a = opts.onException) !== null && _a !== void 0 ? _a : defaultOnException;
  66. const errorHandler = (e) => {
  67. onException(e, span);
  68. span.end();
  69. throw e;
  70. };
  71. try {
  72. const ret = fn(span);
  73. // if fn is an async function, attach a recordException and spanEnd callback to the promise
  74. if (typeof (ret === null || ret === void 0 ? void 0 : ret.then) === 'function') {
  75. return ret.then(val => {
  76. span.end();
  77. return val;
  78. }, errorHandler);
  79. }
  80. span.end();
  81. return ret;
  82. }
  83. catch (e) {
  84. // add throw to signal the compiler that this will throw in the inner scope
  85. throw errorHandler(e);
  86. }
  87. }
  88. //# sourceMappingURL=SugaredTracer.js.map