-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathwrapRouteHandlerWithSentry.ts
116 lines (106 loc) · 4.25 KB
/
wrapRouteHandlerWithSentry.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
import type { RequestEventData } from '@sentry/core';
import {
SEMANTIC_ATTRIBUTE_SENTRY_OP,
SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,
Scope,
captureException,
getActiveSpan,
getCapturedScopesOnSpan,
getIsolationScope,
getRootSpan,
handleCallbackErrors,
propagationContextFromHeaders,
setCapturedScopesOnSpan,
setHttpStatus,
winterCGHeadersToDict,
withIsolationScope,
withScope,
} from '@sentry/core';
import { isNotFoundNavigationError, isRedirectNavigationError } from './nextNavigationErrorUtils';
import type { RouteHandlerContext } from './types';
import { commonObjectToIsolationScope } from './utils/tracingUtils';
/**
* Wraps a Next.js App Router Route handler with Sentry error and performance instrumentation.
*
* NOTICE: This wrapper is for App Router API routes. If you are looking to wrap Pages Router API routes use `wrapApiHandlerWithSentry` instead.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function wrapRouteHandlerWithSentry<F extends (...args: any[]) => any>(
routeHandler: F,
context: RouteHandlerContext,
): (...args: Parameters<F>) => ReturnType<F> extends Promise<unknown> ? ReturnType<F> : Promise<ReturnType<F>> {
const { method, parameterizedRoute, headers } = context;
return new Proxy(routeHandler, {
apply: async (originalFunction, thisArg, args) => {
const activeSpan = getActiveSpan();
const rootSpan = activeSpan ? getRootSpan(activeSpan) : undefined;
let edgeRuntimeIsolationScopeOverride: Scope | undefined;
if (rootSpan && process.env.NEXT_RUNTIME === 'edge') {
const isolationScope = commonObjectToIsolationScope(headers);
const { scope } = getCapturedScopesOnSpan(rootSpan);
setCapturedScopesOnSpan(rootSpan, scope ?? new Scope(), isolationScope);
edgeRuntimeIsolationScopeOverride = isolationScope;
rootSpan.updateName(`${method} ${parameterizedRoute}`);
rootSpan.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, 'route');
rootSpan.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_OP, 'http.server');
}
return withIsolationScope(
process.env.NEXT_RUNTIME === 'edge' ? edgeRuntimeIsolationScopeOverride : getIsolationScope(),
() => {
return withScope(async scope => {
scope.setTransactionName(`${method} ${parameterizedRoute}`);
if (process.env.NEXT_RUNTIME === 'edge') {
const completeHeadersDict: Record<string, string> = headers ? winterCGHeadersToDict(headers) : {};
const incomingPropagationContext = propagationContextFromHeaders(
completeHeadersDict['sentry-trace'],
completeHeadersDict['baggage'],
);
scope.setPropagationContext(incomingPropagationContext);
scope.setSDKProcessingMetadata({
normalizedRequest: {
method,
headers: completeHeadersDict,
} satisfies RequestEventData,
});
}
const response: Response = await handleCallbackErrors(
() => originalFunction.apply(thisArg, args),
error => {
// Next.js throws errors when calling `redirect()`. We don't wanna report these.
if (isRedirectNavigationError(error)) {
// Don't do anything
} else if (isNotFoundNavigationError(error)) {
if (activeSpan) {
setHttpStatus(activeSpan, 404);
}
if (rootSpan) {
setHttpStatus(rootSpan, 404);
}
} else {
captureException(error, {
mechanism: {
handled: false,
},
});
}
},
);
try {
if (response.status) {
if (activeSpan) {
setHttpStatus(activeSpan, response.status);
}
if (rootSpan) {
setHttpStatus(rootSpan, response.status);
}
}
} catch {
// best effort - response may be undefined?
}
return response;
});
},
);
},
});
}