Skip to content

feat(sveltekit): Add server-side handleError wrapper #7411

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Mar 10, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions packages/sveltekit/src/client/handleError.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import type { HandleClientError, NavigationEvent } from '@sveltejs/kit';
*
* @param handleError The original SvelteKit error handler.
*/
export function wrapHandleError(handleError: HandleClientError): HandleClientError {
export function handleErrorWithSentry(handleError?: HandleClientError): HandleClientError {
return (input: { error: unknown; event: NavigationEvent }): ReturnType<HandleClientError> => {
captureException(input.error, scope => {
scope.addEventProcessor(event => {
Expand All @@ -23,6 +23,8 @@ export function wrapHandleError(handleError: HandleClientError): HandleClientErr
});
return scope;
});
return handleError(input);
if (handleError) {
return handleError(input);
}
};
}
2 changes: 1 addition & 1 deletion packages/sveltekit/src/client/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
export * from '@sentry/svelte';

export { init } from './sdk';
export { wrapHandleError } from './handleError';
export { handleErrorWithSentry } from './handleError';

// Just here so that eslint is happy until we export more stuff here
export const PLACEHOLDER_CLIENT = 'PLACEHOLDER';
6 changes: 6 additions & 0 deletions packages/sveltekit/src/index.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,19 @@ export * from './config';
export * from './server';

import type { Integration, Options, StackParser } from '@sentry/types';
// eslint-disable-next-line import/no-unresolved
import type { HandleClientError, HandleServerError } from '@sveltejs/kit';

import type * as clientSdk from './client';
import type * as serverSdk from './server';

/** Initializes Sentry SvelteKit SDK */
export declare function init(options: Options | clientSdk.BrowserOptions | serverSdk.NodeOptions): void;

export declare function handleErrorWithSentry<T extends HandleClientError | HandleServerError>(
handleError: T,
): ReturnType<T>;

// We export a merged Integrations object so that users can (at least typing-wise) use all integrations everywhere.
export declare const Integrations: typeof clientSdk.Integrations & typeof serverSdk.Integrations;

Expand Down
30 changes: 30 additions & 0 deletions packages/sveltekit/src/server/handleError.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { captureException } from '@sentry/node';
import { addExceptionMechanism } from '@sentry/utils';
// For now disable the import/no-unresolved rule, because we don't have a way to
// tell eslint that we are only importing types from the @sveltejs/kit package without
// adding a custom resolver, which will take too much time.
// eslint-disable-next-line import/no-unresolved
import type { HandleServerError, RequestEvent } from '@sveltejs/kit';

/**
* Wrapper for the SvelteKit error handler that sends the error to Sentry.
*
* @param handleError The original SvelteKit error handler.
*/
export function handleErrorWithSentry(handleError?: HandleServerError): HandleServerError {
return (input: { error: unknown; event: RequestEvent }): ReturnType<HandleServerError> => {
captureException(input.error, scope => {
scope.addEventProcessor(event => {
addExceptionMechanism(event, {
type: 'sveltekit',
handled: false,
});
return event;
});
return scope;
});
if (handleError) {
return handleError(input);
}
};
}
1 change: 1 addition & 0 deletions packages/sveltekit/src/server/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export * from '@sentry/node';

export { init } from './sdk';
export { handleErrorWithSentry } from './handleError';
16 changes: 13 additions & 3 deletions packages/sveltekit/test/client/handleError.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { Scope } from '@sentry/svelte';
// eslint-disable-next-line import/no-unresolved
import type { HandleClientError, NavigationEvent } from '@sveltejs/kit';

import { wrapHandleError } from '../../src/client/handleError';
import { handleErrorWithSentry } from '../../src/client/handleError';

const mockCaptureException = jest.fn();
let mockScope = new Scope();
Expand Down Expand Up @@ -55,8 +55,18 @@ describe('handleError', () => {
mockScope = new Scope();
});

it('works when a handleError func is not provided', async () => {
const wrappedHandleError = handleErrorWithSentry();
const mockError = new Error('test');
const returnVal = await wrappedHandleError({ error: mockError, event: navigationEvent });

expect(returnVal).not.toBeDefined();
expect(mockCaptureException).toHaveBeenCalledTimes(1);
expect(mockCaptureException).toHaveBeenCalledWith(mockError, expect.any(Function));
});

it('calls captureException', async () => {
const wrappedHandleError = wrapHandleError(handleError);
const wrappedHandleError = handleErrorWithSentry(handleError);
const mockError = new Error('test');
const returnVal = await wrappedHandleError({ error: mockError, event: navigationEvent });

Expand All @@ -71,7 +81,7 @@ describe('handleError', () => {
return mockScope;
});

const wrappedHandleError = wrapHandleError(handleError);
const wrappedHandleError = handleErrorWithSentry(handleError);
const mockError = new Error('test');
await wrappedHandleError({ error: mockError, event: navigationEvent });

Expand Down
84 changes: 84 additions & 0 deletions packages/sveltekit/test/server/handleError.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import { Scope } from '@sentry/node';
// For now disable the import/no-unresolved rule, because we don't have a way to
// tell eslint that we are only importing types from the @sveltejs/kit package without
// adding a custom resolver, which will take too much time.
// eslint-disable-next-line import/no-unresolved
import type { HandleServerError, RequestEvent } from '@sveltejs/kit';

import { handleErrorWithSentry } from '../../src/server/handleError';

const mockCaptureException = jest.fn();
let mockScope = new Scope();

jest.mock('@sentry/node', () => {
const original = jest.requireActual('@sentry/core');
return {
...original,
captureException: (err: unknown, cb: (arg0: unknown) => unknown) => {
cb(mockScope);
mockCaptureException(err, cb);
return original.captureException(err, cb);
},
};
});

const mockAddExceptionMechanism = jest.fn();

jest.mock('@sentry/utils', () => {
const original = jest.requireActual('@sentry/utils');
return {
...original,
addExceptionMechanism: (...args: unknown[]) => mockAddExceptionMechanism(...args),
};
});

function handleError(_input: { error: unknown; event: RequestEvent }): ReturnType<HandleServerError> {
return {
message: 'Whoops!',
};
}

const requestEvent = {} as RequestEvent;

describe('handleError', () => {
beforeEach(() => {
mockCaptureException.mockClear();
mockAddExceptionMechanism.mockClear();
mockScope = new Scope();
});

it('works when a handleError func is not provided', async () => {
const wrappedHandleError = handleErrorWithSentry();
const mockError = new Error('test');
const returnVal = await wrappedHandleError({ error: mockError, event: requestEvent });

expect(returnVal).not.toBeDefined();
expect(mockCaptureException).toHaveBeenCalledTimes(1);
expect(mockCaptureException).toHaveBeenCalledWith(mockError, expect.any(Function));
});

it('calls captureException', async () => {
const wrappedHandleError = handleErrorWithSentry(handleError);
const mockError = new Error('test');
const returnVal = await wrappedHandleError({ error: mockError, event: requestEvent });

expect(returnVal!.message).toEqual('Whoops!');
expect(mockCaptureException).toHaveBeenCalledTimes(1);
expect(mockCaptureException).toHaveBeenCalledWith(mockError, expect.any(Function));
});

it('adds an exception mechanism', async () => {
const addEventProcessorSpy = jest.spyOn(mockScope, 'addEventProcessor').mockImplementationOnce(callback => {
void callback({}, { event_id: 'fake-event-id' });
return mockScope;
});

const wrappedHandleError = handleErrorWithSentry(handleError);
const mockError = new Error('test');
await wrappedHandleError({ error: mockError, event: requestEvent });

expect(addEventProcessorSpy).toBeCalledTimes(1);
expect(mockAddExceptionMechanism).toBeCalledTimes(1);
expect(mockAddExceptionMechanism).toBeCalledWith({}, { handled: false, type: 'sveltekit' });
});
});