Skip to content

Commit

Permalink
notify sentry within the hook
Browse files Browse the repository at this point in the history
  • Loading branch information
jivey committed Oct 16, 2023
1 parent 39d411e commit 88f2f7d
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 1 deletion.
53 changes: 53 additions & 0 deletions src/hooks.spec.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { render } from '@testing-library/react';
import { useSetAppError } from './hooks';
import sentryTestkit from 'sentry-testkit';
import * as Sentry from '@sentry/react';
import { ErrorContext } from './contexts';

const { testkit, sentryTransport } = sentryTestkit();

describe('useSetAppError', () => {
let setErrorMock: jest.Mock;

beforeEach(() => {
Sentry.init({
dsn: 'https://[email protected]/0',
transport: sentryTransport,
});
setErrorMock = jest.fn();
testkit.reset();
});

it('should capture exception with Sentry and set error', () => {
const ErrorComponent = () => {
useSetAppError()(new Error('test'));
return null;
};

render(
<ErrorContext.Provider value={{ error: null, setError: setErrorMock }}>
<ErrorComponent />
</ErrorContext.Provider>
)
expect(testkit.reports()).toHaveLength(1);
expect(setErrorMock).toHaveBeenCalledWith({
error: new Error('test'),
type: 'Error'
});
});

it('should clear error when called with null', () => {
const ResetComponent = () => {
useSetAppError()(null);
return null;
}
render(
<ErrorContext.Provider value={{ error: null, setError: setErrorMock }}>
<ResetComponent />
</ErrorContext.Provider>
)

expect(testkit.reports()).toHaveLength(0);
expect(setErrorMock).toHaveBeenCalledWith(null);
});
});
6 changes: 5 additions & 1 deletion src/hooks.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
import React from 'react';
import { ErrorContext } from './contexts';
import { getTypeFromError } from './utils';
import * as Sentry from '@sentry/react';

// Convenience hook for manually displaying an app-level error screen.
// Convenience hook for manually displaying an app-level error screen and notifying Sentry.
// Takes a plain error object, or null to clear the error.
export const useSetAppError = () => {
const { setError } = React.useContext(ErrorContext);

return React.useCallback((error: Error | null) => {
if (error) {
Sentry.captureException(error);
}
setError(
// ErrorBoundary expects a wrapped SentryError
error ? {
Expand Down

0 comments on commit 88f2f7d

Please sign in to comment.