|
1 |
| -import { captureException } from '@sentry/svelte'; |
| 1 | +import type { Span } from '@sentry/core'; |
| 2 | +import { captureException, getCurrentHub } from '@sentry/svelte'; |
2 | 3 | import { addExceptionMechanism, isThenable, objectify } from '@sentry/utils';
|
3 |
| -import type { ServerLoad } from '@sveltejs/kit'; |
| 4 | +import type { Load } from '@sveltejs/kit'; |
4 | 5 |
|
5 | 6 | function sendErrorToSentry(e: unknown): unknown {
|
6 | 7 | // In case we have a primitive, wrap it in the equivalent wrapper class (string -> String, etc.) so that we can
|
@@ -30,21 +31,60 @@ function sendErrorToSentry(e: unknown): unknown {
|
30 | 31 | *
|
31 | 32 | * @param origLoad SvelteKit user defined load function
|
32 | 33 | */
|
33 |
| -export function wrapLoadWithSentry(origLoad: ServerLoad): ServerLoad { |
| 34 | +export function wrapLoadWithSentry(origLoad: Load): Load { |
34 | 35 | return new Proxy(origLoad, {
|
35 |
| - apply: (wrappingTarget, thisArg, args: Parameters<ServerLoad>) => { |
| 36 | + apply: (wrappingTarget, thisArg, args: Parameters<Load>) => { |
36 | 37 | let maybePromiseResult;
|
37 | 38 |
|
| 39 | + const [event] = args; |
| 40 | + |
| 41 | + const scope = getCurrentHub().getScope(); |
| 42 | + |
| 43 | + let activeSpan: Span | undefined = undefined; |
| 44 | + let parentSpan: Span | undefined = undefined; |
| 45 | + |
| 46 | + if (scope) { |
| 47 | + parentSpan = scope.getSpan(); |
| 48 | + if (parentSpan) { |
| 49 | + activeSpan = parentSpan.startChild({ |
| 50 | + op: 'function.sveltekit.load', |
| 51 | + description: event.route.id || '/', |
| 52 | + }); |
| 53 | + |
| 54 | + scope.setSpan(activeSpan); |
| 55 | + } |
| 56 | + } |
| 57 | + |
38 | 58 | try {
|
39 | 59 | maybePromiseResult = wrappingTarget.apply(thisArg, args);
|
40 | 60 | } catch (e) {
|
41 |
| - throw sendErrorToSentry(e); |
| 61 | + if (activeSpan) { |
| 62 | + activeSpan.setStatus('internal_error'); |
| 63 | + activeSpan.finish(); |
| 64 | + } |
| 65 | + const sentryError = sendErrorToSentry(e); |
| 66 | + throw sentryError; |
42 | 67 | }
|
43 | 68 |
|
44 | 69 | if (isThenable(maybePromiseResult)) {
|
45 |
| - Promise.resolve(maybePromiseResult).then(null, e => { |
46 |
| - sendErrorToSentry(e); |
47 |
| - }); |
| 70 | + Promise.resolve(maybePromiseResult).then( |
| 71 | + () => { |
| 72 | + if (activeSpan) { |
| 73 | + activeSpan.finish(); |
| 74 | + } |
| 75 | + }, |
| 76 | + e => { |
| 77 | + if (activeSpan) { |
| 78 | + activeSpan.setStatus('internal_error'); |
| 79 | + activeSpan.finish(); |
| 80 | + } |
| 81 | + sendErrorToSentry(e); |
| 82 | + }, |
| 83 | + ); |
| 84 | + } else { |
| 85 | + if (activeSpan) { |
| 86 | + activeSpan.finish(); |
| 87 | + } |
48 | 88 | }
|
49 | 89 |
|
50 | 90 | return maybePromiseResult;
|
|
0 commit comments