Skip to content

Commit 93bbeb7

Browse files
authored
fix(node): Capture errors in tRPC middleware (#9782)
1 parent b3f8d9b commit 93bbeb7

File tree

1 file changed

+14
-18
lines changed

1 file changed

+14
-18
lines changed

packages/node/src/handlers.ts

+14-18
Original file line numberDiff line numberDiff line change
@@ -351,36 +351,32 @@ export function trpcMiddleware(options: SentryTrpcMiddlewareOptions = {}) {
351351
sentryTransaction.setContext('trpc', trpcContext);
352352
}
353353

354-
function shouldCaptureError(e: unknown): boolean {
355-
if (typeof e === 'object' && e && 'code' in e) {
356-
// Is likely TRPCError - we only want to capture internal server errors
357-
return e.code === 'INTERNAL_SERVER_ERROR';
358-
} else {
359-
// Is likely random error that bubbles up
360-
return true;
361-
}
362-
}
363-
364-
function handleErrorCase(e: unknown): void {
365-
if (shouldCaptureError(e)) {
366-
captureException(e, { mechanism: { handled: false } });
354+
function captureIfError(nextResult: { ok: false; error?: Error } | { ok: true }): void {
355+
if (!nextResult.ok) {
356+
captureException(nextResult.error, { mechanism: { handled: false, data: { function: 'trpcMiddleware' } } });
367357
}
368358
}
369359

370360
let maybePromiseResult;
371-
372361
try {
373362
maybePromiseResult = next();
374363
} catch (e) {
375-
handleErrorCase(e);
364+
captureException(e, { mechanism: { handled: false, data: { function: 'trpcMiddleware' } } });
376365
throw e;
377366
}
378367

379368
if (isThenable(maybePromiseResult)) {
380369
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
381-
Promise.resolve(maybePromiseResult).then(null, e => {
382-
handleErrorCase(e);
383-
});
370+
Promise.resolve(maybePromiseResult).then(
371+
nextResult => {
372+
captureIfError(nextResult as any);
373+
},
374+
e => {
375+
captureException(e, { mechanism: { handled: false, data: { function: 'trpcMiddleware' } } });
376+
},
377+
);
378+
} else {
379+
captureIfError(maybePromiseResult as any);
384380
}
385381

386382
// We return the original promise just to be safe.

0 commit comments

Comments
 (0)