Skip to content

Commit 742e9a1

Browse files
committed
feat(sveltekit): Add performance monitoring for client load
1 parent 4434d60 commit 742e9a1

File tree

1 file changed

+48
-8
lines changed
  • packages/sveltekit/src/client

1 file changed

+48
-8
lines changed

packages/sveltekit/src/client/load.ts

Lines changed: 48 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
1-
import { captureException } from '@sentry/svelte';
1+
import type { Span } from '@sentry/core';
2+
import { captureException, getCurrentHub } from '@sentry/svelte';
23
import { addExceptionMechanism, isThenable, objectify } from '@sentry/utils';
3-
import type { ServerLoad } from '@sveltejs/kit';
4+
import type { Load } from '@sveltejs/kit';
45

56
function sendErrorToSentry(e: unknown): unknown {
67
// 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 {
3031
*
3132
* @param origLoad SvelteKit user defined load function
3233
*/
33-
export function wrapLoadWithSentry(origLoad: ServerLoad): ServerLoad {
34+
export function wrapLoadWithSentry(origLoad: Load): Load {
3435
return new Proxy(origLoad, {
35-
apply: (wrappingTarget, thisArg, args: Parameters<ServerLoad>) => {
36+
apply: (wrappingTarget, thisArg, args: Parameters<Load>) => {
3637
let maybePromiseResult;
3738

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+
3858
try {
3959
maybePromiseResult = wrappingTarget.apply(thisArg, args);
4060
} 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;
4267
}
4368

4469
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+
}
4888
}
4989

5090
return maybePromiseResult;

0 commit comments

Comments
 (0)