Skip to content

Commit

Permalink
fix(node): Capture errors in tRPC middleware (#9782)
Browse files Browse the repository at this point in the history
  • Loading branch information
lforst authored Dec 11, 2023
1 parent b3f8d9b commit 93bbeb7
Showing 1 changed file with 14 additions and 18 deletions.
32 changes: 14 additions & 18 deletions packages/node/src/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down

0 comments on commit 93bbeb7

Please sign in to comment.