Skip to content

fix(node): Capture errors in tRPC middleware #9782

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Dec 11, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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