@@ -391,24 +391,46 @@ function wrapPromise (state, node) {
391391 try {
392392 let promise = __apm$traced();
393393 if (typeof promise?.then !== 'function') {
394- __apm$ctx.result = promise;
394+ __apm$ctx.result = promise;
395395 return promise;
396396 }
397- return promise.then(
397+ // Mirror Node.js core diagnostics_channel behaviour: for native Promise
398+ // instances, chain normally (safe since there is no subclass API to
399+ // preserve). For Promise subclasses and other thenables, side-chain the
400+ // callbacks for event publishing and return the original so that any
401+ // subclass-specific methods (e.g. APIPromise.withResponse()) remain
402+ // accessible to the caller.
403+ if (promise instanceof Promise && promise.constructor === Promise) {
404+ return promise.then(
405+ result => {
406+ __apm$ctx.result = result;
407+ ${ channelVariable } .asyncStart.publish(__apm$ctx);
408+ ${ channelVariable } .asyncEnd.publish(__apm$ctx);
409+ return result;
410+ },
411+ err => {
412+ __apm$ctx.error = err;
413+ ${ channelVariable } .error.publish(__apm$ctx);
414+ ${ channelVariable } .asyncStart.publish(__apm$ctx);
415+ ${ channelVariable } .asyncEnd.publish(__apm$ctx);
416+ throw err;
417+ }
418+ );
419+ }
420+ promise.then(
398421 result => {
399422 __apm$ctx.result = result;
400423 ${ channelVariable } .asyncStart.publish(__apm$ctx);
401424 ${ channelVariable } .asyncEnd.publish(__apm$ctx);
402- return result;
403425 },
404426 err => {
405427 __apm$ctx.error = err;
406428 ${ channelVariable } .error.publish(__apm$ctx);
407429 ${ channelVariable } .asyncStart.publish(__apm$ctx);
408430 ${ channelVariable } .asyncEnd.publish(__apm$ctx);
409- throw err;
410431 }
411432 );
433+ return promise;
412434 } catch (err) {
413435 __apm$ctx.error = err;
414436 ${ channelVariable } .error.publish(__apm$ctx);
0 commit comments