@@ -303,7 +303,30 @@ export class Server extends TypedEventEmitter<ServerEvents> {
303
303
}
304
304
}
305
305
306
- const cmd = operation . buildCommand ( conn , session ) ;
306
+ let reauthPromise : Promise < void > | null = null ;
307
+ const cleanup = ( ) => {
308
+ this . decrementOperationCount ( ) ;
309
+ if ( session ?. pinnedConnection !== conn ) {
310
+ if ( reauthPromise != null ) {
311
+ // The reauth promise only exists if it hasn't thrown.
312
+ const checkBackIn = ( ) => {
313
+ this . pool . checkIn ( conn ) ;
314
+ } ;
315
+ void reauthPromise . then ( checkBackIn , checkBackIn ) ;
316
+ } else {
317
+ this . pool . checkIn ( conn ) ;
318
+ }
319
+ }
320
+ } ;
321
+
322
+ let cmd ;
323
+ try {
324
+ cmd = operation . buildCommand ( conn , session ) ;
325
+ } catch ( e ) {
326
+ cleanup ( ) ;
327
+ throw e ;
328
+ }
329
+
307
330
const options = operation . buildOptions ( timeoutContext ) ;
308
331
const ns = operation . ns ;
309
332
@@ -325,8 +348,6 @@ export class Server extends TypedEventEmitter<ServerEvents> {
325
348
options . omitMaxTimeMS = true ;
326
349
}
327
350
328
- let reauthPromise : Promise < void > | null = null ;
329
-
330
351
try {
331
352
try {
332
353
const res = await conn . command ( ns , cmd , options , operation . SERVER_COMMAND_RESPONSE_TYPE ) ;
@@ -360,18 +381,7 @@ export class Server extends TypedEventEmitter<ServerEvents> {
360
381
throw operationError ;
361
382
}
362
383
} finally {
363
- this . decrementOperationCount ( ) ;
364
- if ( session ?. pinnedConnection !== conn ) {
365
- if ( reauthPromise != null ) {
366
- // The reauth promise only exists if it hasn't thrown.
367
- const checkBackIn = ( ) => {
368
- this . pool . checkIn ( conn ) ;
369
- } ;
370
- void reauthPromise . then ( checkBackIn , checkBackIn ) ;
371
- } else {
372
- this . pool . checkIn ( conn ) ;
373
- }
374
- }
384
+ cleanup ( ) ;
375
385
}
376
386
}
377
387
0 commit comments