From 93bbeb782ae588aee2d021a7eba3cd6d946e69be Mon Sep 17 00:00:00 2001 From: Luca Forstner Date: Mon, 11 Dec 2023 12:51:41 +0100 Subject: [PATCH] fix(node): Capture errors in tRPC middleware (#9782) --- packages/node/src/handlers.ts | 32 ++++++++++++++------------------ 1 file changed, 14 insertions(+), 18 deletions(-) diff --git a/packages/node/src/handlers.ts b/packages/node/src/handlers.ts index 83f23ccaec7c..3160c77b416a 100644 --- a/packages/node/src/handlers.ts +++ b/packages/node/src/handlers.ts @@ -351,36 +351,32 @@ export function trpcMiddleware(options: SentryTrpcMiddlewareOptions = {}) { sentryTransaction.setContext('trpc', trpcContext); } - function shouldCaptureError(e: unknown): boolean { - if (typeof e === 'object' && e && 'code' in e) { - // Is likely TRPCError - we only want to capture internal server errors - return e.code === 'INTERNAL_SERVER_ERROR'; - } else { - // Is likely random error that bubbles up - return true; - } - } - - function handleErrorCase(e: unknown): void { - if (shouldCaptureError(e)) { - captureException(e, { mechanism: { handled: false } }); + function captureIfError(nextResult: { ok: false; error?: Error } | { ok: true }): void { + if (!nextResult.ok) { + captureException(nextResult.error, { mechanism: { handled: false, data: { function: 'trpcMiddleware' } } }); } } let maybePromiseResult; - try { maybePromiseResult = next(); } catch (e) { - handleErrorCase(e); + captureException(e, { mechanism: { handled: false, data: { function: 'trpcMiddleware' } } }); throw e; } if (isThenable(maybePromiseResult)) { // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - Promise.resolve(maybePromiseResult).then(null, e => { - handleErrorCase(e); - }); + Promise.resolve(maybePromiseResult).then( + nextResult => { + captureIfError(nextResult as any); + }, + e => { + captureException(e, { mechanism: { handled: false, data: { function: 'trpcMiddleware' } } }); + }, + ); + } else { + captureIfError(maybePromiseResult as any); } // We return the original promise just to be safe.