Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 13 additions & 3 deletions packages/core/src/tracing/trace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@ import type { TransactionContext } from '@sentry/types';
import { isThenable } from '@sentry/utils';

import { getCurrentHub } from '../hub';
import { hasTracingEnabled } from '../utils/hasTracingEnabled';
import type { Span } from './span';

/**
* Wraps a function with a transaction/span and finishes the span after the function is done.
*
* Note that if you have not enabled tracing extensions via `addTracingExtensions`, this function
* will not generate spans, and the `span` returned from the callback may be undefined.
* Note that if you have not enabled tracing extensions via `addTracingExtensions`
* or you didn't set `tracesSampleRate`, this function will not generate spans
* and the `span` returned from the callback will be undefined.
*
* This function is meant to be used internally and may break at any time. Use at your own risk.
*
Expand All @@ -31,7 +33,15 @@ export function trace<T>(
const scope = hub.getScope();

const parentSpan = scope.getSpan();
const activeSpan = parentSpan ? parentSpan.startChild(ctx) : hub.startTransaction(ctx);

function getActiveSpan(): Span | undefined {
if (!hasTracingEnabled()) {
return undefined;
}
return parentSpan ? parentSpan.startChild(ctx) : hub.startTransaction(ctx);
}

const activeSpan = getActiveSpan();
scope.setSpan(activeSpan);

function finishAndSetSpan(): void {
Expand Down
28 changes: 28 additions & 0 deletions packages/core/test/lib/tracing/trace.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -185,5 +185,33 @@ describe('trace', () => {
}
expect(onError).toHaveBeenCalledTimes(isError ? 1 : 0);
});

it("doesn't create spans but calles onError if tracing is disabled", async () => {
const options = getDefaultTestClientOptions({
/* we don't set tracesSampleRate or tracesSampler */
});
client = new TestClient(options);
hub = new Hub(client);
makeMain(hub);

const startTxnSpy = jest.spyOn(hub, 'startTransaction');

const onError = jest.fn();
try {
await trace(
{ name: 'GET users/[id]' },
() => {
return callback();
},
onError,
);
} catch (e) {
expect(onError).toHaveBeenCalledTimes(1);
expect(onError).toHaveBeenCalledWith(e);
}
expect(onError).toHaveBeenCalledTimes(isError ? 1 : 0);

expect(startTxnSpy).not.toHaveBeenCalled();
});
});
});