Skip to content

Commit 8b84905

Browse files
authored
feat(node): Capture internal server errors in trpc middleware (#9482)
1 parent be44a21 commit 8b84905

File tree

1 file changed

+31
-2
lines changed

1 file changed

+31
-2
lines changed

packages/node/src/handlers.ts

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -338,7 +338,7 @@ interface TrpcMiddlewareArguments<T> {
338338
* e.g. Express Request Handlers or Next.js SDK.
339339
*/
340340
export function trpcMiddleware(options: SentryTrpcMiddlewareOptions = {}) {
341-
return function <T>({ path, type, next, rawInput }: TrpcMiddlewareArguments<T>): T {
341+
return async function <T>({ path, type, next, rawInput }: TrpcMiddlewareArguments<T>): Promise<T> {
342342
const hub = getCurrentHub();
343343
const clientOptions = hub.getClient()?.getOptions();
344344
const sentryTransaction = hub.getScope().getTransaction();
@@ -358,7 +358,36 @@ export function trpcMiddleware(options: SentryTrpcMiddlewareOptions = {}) {
358358
sentryTransaction.setContext('trpc', trpcContext);
359359
}
360360

361-
return next();
361+
function captureError(e: unknown): void {
362+
captureException(e, scope => {
363+
scope.addEventProcessor(event => {
364+
addExceptionMechanism(event, {
365+
handled: false,
366+
});
367+
return event;
368+
});
369+
370+
return scope;
371+
});
372+
}
373+
374+
try {
375+
return await next();
376+
} catch (e: unknown) {
377+
if (typeof e === 'object' && e) {
378+
if ('code' in e) {
379+
// Is likely TRPCError - we only want to capture internal server errors
380+
if (e.code === 'INTERNAL_SERVER_ERROR') {
381+
captureError(e);
382+
}
383+
} else {
384+
// Is likely random error that bubbles up
385+
captureError(e);
386+
}
387+
}
388+
389+
throw e;
390+
}
362391
};
363392
}
364393

0 commit comments

Comments
 (0)