From 1b08f203ea446391e3836ac213e3a715762acd23 Mon Sep 17 00:00:00 2001 From: Justin Spahr-Summers Date: Thu, 14 Nov 2024 14:02:51 +0000 Subject: [PATCH] Catch errors that occur when a handler is invoked, but before it returns a Promise --- src/shared/protocol.ts | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/src/shared/protocol.ts b/src/shared/protocol.ts index 752d2cc0..ab8421bf 100644 --- a/src/shared/protocol.ts +++ b/src/shared/protocol.ts @@ -190,11 +190,14 @@ export abstract class Protocol< return; } - handler(notification).catch((error) => - this._onerror( - new Error(`Uncaught error in notification handler: ${error}`), - ), - ); + // Starting with Promise.resolve() puts any synchronous errors into the monad as well. + Promise.resolve() + .then(() => handler(notification)) + .catch((error) => + this._onerror( + new Error(`Uncaught error in notification handler: ${error}`), + ), + ); } private _onrequest(request: JSONRPCRequest): void { @@ -222,7 +225,9 @@ export abstract class Protocol< const abortController = new AbortController(); this._requestHandlerAbortControllers.set(request.id, abortController); - handler(request, { signal: abortController.signal }) + // Starting with Promise.resolve() puts any synchronous errors into the monad as well. + Promise.resolve() + .then(() => handler(request, { signal: abortController.signal })) .then( (result) => { if (abortController.signal.aborted) {