@@ -116,32 +116,41 @@ type WrappedResponseEndMethod = AugmentedNextApiResponse['end'];
116
116
117
117
function wrapEndMethod ( origEnd : ResponseEndMethod ) : WrappedResponseEndMethod {
118
118
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 ) ;
144
120
145
121
return origEnd . call ( this , ...args ) ;
146
122
} ;
147
123
}
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