Skip to content

Commit 91a8612

Browse files
committed
allow for finish to be passed in callback
1 parent 699329e commit 91a8612

File tree

1 file changed

+20
-3
lines changed

1 file changed

+20
-3
lines changed

packages/core/src/tracing/trace.ts

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -143,7 +143,16 @@ export function startActiveSpan<T>(context: TransactionContext, callback: (span:
143143

144144
/**
145145
* Similar to `Sentry.startActiveSpan`. Wraps a function with a transaction/span, but does not finish the span
146-
* after the function is done automatically.
146+
* after the function is done automatically. Use the returned `finish` function to finish the span.
147+
*
148+
* ```js
149+
* Sentry.startActiveSpan({ name: 'foo' }, (span, finish) => {
150+
* // do work here
151+
* res.on('finish', () => {
152+
* finish();
153+
* });
154+
* });
155+
* ```
147156
*
148157
* The created span is the active span and will be used as parent by other spans created inside the function
149158
* and can be accessed via `Sentry.getSpan()`, as long as the function is executed while the scope is active.
@@ -152,7 +161,10 @@ export function startActiveSpan<T>(context: TransactionContext, callback: (span:
152161
* or you didn't set `tracesSampleRate`, this function will not generate spans
153162
* and the `span` returned from the callback will be undefined.
154163
*/
155-
export function startActiveSpanManual<T>(context: TransactionContext, callback: (span: Span | undefined) => T): T {
164+
export function startActiveSpanManual<T>(
165+
context: TransactionContext,
166+
callback: (span: Span | undefined, finish: () => void) => T,
167+
): T {
156168
const ctx = { ...context };
157169
// If a name is set and a description is not, set the description to the name.
158170
if (ctx.name !== undefined && ctx.description === undefined) {
@@ -174,9 +186,14 @@ export function startActiveSpanManual<T>(context: TransactionContext, callback:
174186
const activeSpan = getChildSpanOrTransaction();
175187
scope.setSpan(activeSpan);
176188

189+
function finishAndSetSpan(): void {
190+
activeSpan && activeSpan.finish();
191+
hub.getScope().setSpan(parentSpan);
192+
}
193+
177194
let maybePromiseResult: T;
178195
try {
179-
maybePromiseResult = callback(activeSpan);
196+
maybePromiseResult = callback(activeSpan, finishAndSetSpan);
180197
} catch (e) {
181198
activeSpan && activeSpan.setStatus('internal_error');
182199
throw e;

0 commit comments

Comments
 (0)