(options: SentryTrpcMiddlewareOptions = {})
| 40 | * Sentry tRPC middleware that captures errors and creates spans for tRPC procedures. |
| 41 | */ |
| 42 | export function trpcMiddleware(options: SentryTrpcMiddlewareOptions = {}) { |
| 43 | // eslint-disable-next-line @typescript-eslint/ban-ts-comment |
| 44 | // @ts-ignore |
| 45 | return async function <T>(opts: SentryTrpcMiddlewareArguments<T>): SentryTrpcMiddleware<T> { |
| 46 | const { path, type, next, rawInput, getRawInput } = opts; |
| 47 | |
| 48 | const client = getClient(); |
| 49 | const clientOptions = client?.getOptions(); |
| 50 | const dataCollection = client?.getDataCollectionOptions(); |
| 51 | |
| 52 | const trpcContext: Record<string, unknown> = { |
| 53 | procedure_path: path, |
| 54 | procedure_type: type, |
| 55 | }; |
| 56 | |
| 57 | setNormalizationDepthOverrideHint( |
| 58 | trpcContext, |
| 59 | 1 + // 1 for context.input + the normal normalization depth |
| 60 | (clientOptions?.normalizeDepth ?? 5), // 5 is a sane depth |
| 61 | ); |
| 62 | |
| 63 | if ( |
| 64 | options.attachRpcInput !== undefined |
| 65 | ? options.attachRpcInput |
| 66 | : dataCollection?.httpBodies.includes('incomingRequest') |
| 67 | ) { |
| 68 | if (rawInput !== undefined) { |
| 69 | trpcContext.input = normalize(rawInput); |
| 70 | } |
| 71 | |
| 72 | if (getRawInput !== undefined && typeof getRawInput === 'function') { |
| 73 | try { |
| 74 | const rawRes = await getRawInput(); |
| 75 | |
| 76 | trpcContext.input = normalize(rawRes); |
| 77 | } catch { |
| 78 | // noop |
| 79 | } |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | return withIsolationScope(scope => { |
| 84 | scope.setContext('trpc', trpcContext); |
| 85 | return startSpanManual( |
| 86 | { |
| 87 | name: `trpc/${path}`, |
| 88 | op: 'rpc.server', |
| 89 | attributes: { |
| 90 | [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'route', |
| 91 | [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.rpc.trpc', |
| 92 | }, |
| 93 | forceTransaction: !!options.forceTransaction, |
| 94 | }, |
| 95 | async span => { |
| 96 | try { |
| 97 | const nextResult = await next(); |
| 98 | captureIfError(nextResult); |
| 99 | span.end(); |
no test coverage detected