Skip to content

Commit d5b4b4e

Browse files
committed
pull cleanup work out into its own function
1 parent ebaebb7 commit d5b4b4e

File tree

1 file changed

+34
-25
lines changed

1 file changed

+34
-25
lines changed

packages/nextjs/src/utils/withSentry.ts

Lines changed: 34 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -116,32 +116,41 @@ type WrappedResponseEndMethod = AugmentedNextApiResponse['end'];
116116

117117
function wrapEndMethod(origEnd: ResponseEndMethod): WrappedResponseEndMethod {
118118
return async function newEnd(this: AugmentedNextApiResponse, ...args: unknown[]) {
119-
const transaction = this.__sentryTransaction;
120-
121-
if (transaction) {
122-
transaction.setHttpStatus(this.statusCode);
123-
124-
// Push `transaction.finish` to the next event loop so open spans have a better chance of finishing before the
125-
// transaction closes, and make sure to wait until that's done before flushing events
126-
const transactionFinished: Promise<void> = new Promise(resolve => {
127-
setImmediate(() => {
128-
transaction.finish();
129-
resolve();
130-
});
131-
});
132-
await transactionFinished;
133-
}
134-
135-
// flush the event queue to ensure that events get sent to Sentry before the response is finished and the lambda
136-
// ends
137-
try {
138-
logger.log('Flushing events...');
139-
await flush(2000);
140-
logger.log('Done flushing events');
141-
} catch (e) {
142-
logger.log(`Error while flushing events:\n${e}`);
143-
}
119+
await finishSentryProcessing(this);
144120

145121
return origEnd.call(this, ...args);
146122
};
147123
}
124+
125+
/**
126+
* Close the open transaction (if any) and flush events to Sentry.
127+
*
128+
* @param res The outgoing response for this request, on which the transaction is stored
129+
*/
130+
async function finishSentryProcessing(res: AugmentedNextApiResponse): Promise<void> {
131+
const { __sentryTransaction: transaction } = res;
132+
133+
if (transaction) {
134+
transaction.setHttpStatus(res.statusCode);
135+
136+
// Push `transaction.finish` to the next event loop so open spans have a better chance of finishing before the
137+
// transaction closes, and make sure to wait until that's done before flushing events
138+
const transactionFinished: Promise<void> = new Promise(resolve => {
139+
setImmediate(() => {
140+
transaction.finish();
141+
resolve();
142+
});
143+
});
144+
await transactionFinished;
145+
}
146+
147+
// Flush the event queue to ensure that events get sent to Sentry before the response is finished and the lambda
148+
// ends. If there was an error, rethrow it so that the normal exception-handling mechanisms can apply.
149+
try {
150+
logger.log('Flushing events...');
151+
await flush(2000);
152+
logger.log('Done flushing events');
153+
} catch (e) {
154+
logger.log(`Error while flushing events:\n${e}`);
155+
}
156+
}

0 commit comments

Comments
 (0)