|
| 1 | +import { SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, startSpan } from '@sentry/node'; |
| 2 | +import { addNonEnumerableProperty } from '@sentry/utils'; |
| 3 | +import type { RequestEvent } from '@sveltejs/kit'; |
| 4 | +import { flushIfServerless, sendErrorToSentry } from './utils'; |
| 5 | + |
| 6 | +type PatchedServerRouteEvent = RequestEvent & { __sentry_wrapped__?: boolean }; |
| 7 | + |
| 8 | +/** |
| 9 | + * Wraps a server route handler for API or server routes registered in `+server.(js|js)` files. |
| 10 | + * |
| 11 | + * This function will automatically capture any errors that occur during the execution of the route handler |
| 12 | + * and it will start a span for the duration of your route handler. |
| 13 | + * |
| 14 | + * @example |
| 15 | + * ```js |
| 16 | + * import { wrapServerRouteWithSentry } from '@sentry/sveltekit'; |
| 17 | + * |
| 18 | + * const get = async event => { |
| 19 | + * return new Response(JSON.stringify({ message: 'hello world' })); |
| 20 | + * } |
| 21 | + * |
| 22 | + * export const GET = wrapServerRouteWithSentry(get); |
| 23 | + * ``` |
| 24 | + * |
| 25 | + * @param originalRouteHandler your server route handler |
| 26 | + * @param httpMethod the HTTP method of your route handler |
| 27 | + * |
| 28 | + * @returns a wrapped version of your server route handler |
| 29 | + */ |
| 30 | +export function wrapServerRouteWithSentry( |
| 31 | + originalRouteHandler: (request: RequestEvent) => Promise<Response>, |
| 32 | +): (requestEvent: RequestEvent) => Promise<Response> { |
| 33 | + return new Proxy(originalRouteHandler, { |
| 34 | + apply: async (wrappingTarget, thisArg, args) => { |
| 35 | + const event = args[0] as PatchedServerRouteEvent; |
| 36 | + |
| 37 | + if (event.__sentry_wrapped__) { |
| 38 | + return wrappingTarget.apply(thisArg, args); |
| 39 | + } |
| 40 | + |
| 41 | + const routeId = event.route && event.route.id; |
| 42 | + const httpMethod = event.request.method; |
| 43 | + |
| 44 | + addNonEnumerableProperty(event as unknown as Record<string, unknown>, '__sentry_wrapped__', true); |
| 45 | + |
| 46 | + try { |
| 47 | + return await startSpan( |
| 48 | + { |
| 49 | + name: `${httpMethod} ${routeId || 'Server Route'}`, |
| 50 | + op: `function.sveltekit.server.${httpMethod.toLowerCase()}`, |
| 51 | + attributes: { |
| 52 | + [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.function.sveltekit', |
| 53 | + [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'route', |
| 54 | + }, |
| 55 | + onlyIfParent: true, |
| 56 | + }, |
| 57 | + () => wrappingTarget.apply(thisArg, args), |
| 58 | + ); |
| 59 | + } catch (e) { |
| 60 | + sendErrorToSentry(e, 'serverRoute'); |
| 61 | + throw e; |
| 62 | + } finally { |
| 63 | + await flushIfServerless(); |
| 64 | + } |
| 65 | + }, |
| 66 | + }); |
| 67 | +} |
0 commit comments