Skip to content
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
2 changes: 1 addition & 1 deletion packages/browser/src/BacktraceClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ export class BacktraceClient<O extends BacktraceConfiguration = BacktraceConfigu
new BacktraceReport(
errorEvent.reason,
{
'error.type': 'Unhandled exception',
'error.type': 'Unhandled rejection',
},
[],
{
Expand Down
65 changes: 65 additions & 0 deletions packages/browser/tests/client/unhandledErrorTests.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import { BacktraceRequestHandler } from '@backtrace/sdk-core';
import { BacktraceClient } from '../../src/index.js';

describe('Unhandled error/rejection labeling', () => {
let postedJson: string | undefined;
let requestHandler: BacktraceRequestHandler;
let client: BacktraceClient;

const defaultClientOptions = {
name: 'test',
version: '1.0.0',
url: 'https://submit.backtrace.io/foo/bar/baz',
metrics: { enable: false },
breadcrumbs: { enable: false },
};

beforeEach(() => {
postedJson = undefined;
requestHandler = {
post: jest.fn().mockResolvedValue(Promise.resolve()),
postError: jest.fn().mockImplementation((_url: string, json: string) => {
postedJson = json;
return Promise.resolve();
}),
};
client = BacktraceClient.builder(defaultClientOptions).useRequestHandler(requestHandler).build();
});

afterEach(() => {
client.dispose();
});

const flushMicrotasks = () => new Promise((resolve) => setTimeout(resolve, 0));

it("Should tag synthetic 'unhandledrejection' events with error.type 'Unhandled rejection'", async () => {
const event = new Event('unhandledrejection') as PromiseRejectionEvent;
Object.defineProperty(event, 'reason', { value: new TypeError('Failed to fetch') });
Object.defineProperty(event, 'promise', { value: Promise.resolve() });
window.dispatchEvent(event);

await flushMicrotasks();

expect(requestHandler.postError).toHaveBeenCalled();
expect(postedJson).toBeDefined();
const payload = JSON.parse(postedJson as string);
expect(payload.attributes['error.type']).toBe('Unhandled rejection');
expect(payload.classifiers).toContain('UnhandledPromiseRejection');
});

it("Should tag synthetic 'error' events with error.type 'Unhandled exception'", async () => {
const event = new ErrorEvent('error', {
error: new Error('boom'),
message: 'boom',
});
window.dispatchEvent(event);

await flushMicrotasks();

expect(requestHandler.postError).toHaveBeenCalled();
expect(postedJson).toBeDefined();
const payload = JSON.parse(postedJson as string);
expect(payload.attributes['error.type']).toBe('Unhandled exception');
expect(payload.classifiers ?? []).not.toContain('UnhandledPromiseRejection');
});
});
17 changes: 13 additions & 4 deletions packages/node/src/BacktraceClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,10 +128,19 @@ export class BacktraceClient extends BacktraceCoreClient<BacktraceConfiguration>
if (origin === 'uncaughtException' && !captureUnhandledExceptions) {
return;
}
const isRejection = origin === 'unhandledRejection';
await this.send(
new BacktraceReport(error, { 'error.type': 'Unhandled exception', errorOrigin: origin }, [], {
classifiers: origin === 'unhandledRejection' ? ['UnhandledPromiseRejection'] : undefined,
}),
new BacktraceReport(
error,
{
'error.type': isRejection ? 'Unhandled rejection' : 'Unhandled exception',
errorOrigin: origin,
},
[],
{
classifiers: isRejection ? ['UnhandledPromiseRejection'] : undefined,
},
),
);
};

Expand Down Expand Up @@ -170,7 +179,7 @@ export class BacktraceClient extends BacktraceCoreClient<BacktraceConfiguration>
new BacktraceReport(
isErrorTypeReason ? reason : (reason?.toString() ?? 'Unhandled rejection'),
{
'error.type': 'Unhandled exception',
'error.type': 'Unhandled rejection',
},
[],
{
Expand Down
101 changes: 101 additions & 0 deletions packages/node/tests/client/unhandledErrorTests.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
import { BacktraceRequestHandler } from '@backtrace/sdk-core';
import { BacktraceClient } from '../../src/index.js';
import { NodeOptionReader } from '../../src/common/NodeOptionReader.js';

Comment thread
melekr marked this conversation as resolved.
describe('Unhandled error/rejection labeling', () => {
let postedJson: string | undefined;
let requestHandler: BacktraceRequestHandler;
let client: BacktraceClient;

const defaultClientOptions = {
url: 'https://submit.backtrace.io/foo/bar/baz',
metrics: { enable: false },
breadcrumbs: { enable: false },
};

const flushMicrotasks = () => new Promise((resolve) => setTimeout(resolve, 0));

const buildClient = () => {
postedJson = undefined;
requestHandler = {
post: jest.fn().mockResolvedValue(Promise.resolve()),
postError: jest.fn().mockImplementation((_url: string, json: string) => {
postedJson = json;
return Promise.resolve();
}),
};
return BacktraceClient.builder(defaultClientOptions).useRequestHandler(requestHandler).build();
};

describe('uncaughtExceptionMonitor callback', () => {
beforeEach(() => {
client = buildClient();
});

afterEach(() => {
client.dispose();
});

it("Should tag origin 'unhandledRejection' as 'Unhandled rejection'", async () => {
(process as unknown as { emit: (e: string, ...args: unknown[]) => void }).emit(
'uncaughtExceptionMonitor',
new Error('rejected'),
'unhandledRejection',
);
await flushMicrotasks();

expect(requestHandler.postError).toHaveBeenCalled();
const payload = JSON.parse(postedJson as string);
expect(payload.attributes['error.type']).toBe('Unhandled rejection');
expect(payload.classifiers).toContain('UnhandledPromiseRejection');
});

it("Should tag origin 'uncaughtException' as 'Unhandled exception'", async () => {
(process as unknown as { emit: (e: string, ...args: unknown[]) => void }).emit(
'uncaughtExceptionMonitor',
new Error('boom'),
'uncaughtException',
);
await flushMicrotasks();

expect(requestHandler.postError).toHaveBeenCalled();
const payload = JSON.parse(postedJson as string);
expect(payload.attributes['error.type']).toBe('Unhandled exception');
expect(payload.classifiers ?? []).not.toContain('UnhandledPromiseRejection');
});
});

describe("dedicated 'unhandledRejection' listener", () => {
let nodeOptionReaderSpy: jest.SpyInstance;

beforeEach(() => {
// Force the dedicated unhandledRejection listener to be registered.
// See BacktraceClient.captureUnhandledErrors: the listener is skipped
// when running on Node 15+ with default --unhandled-rejections behavior.
nodeOptionReaderSpy = jest.spyOn(NodeOptionReader, 'read').mockImplementation((flag: string) => {
if (flag === 'unhandled-rejections') return 'warn';
return undefined;
});
client = buildClient();
});

afterEach(() => {
client.dispose();
nodeOptionReaderSpy.mockRestore();
});

it("Should tag emitted 'unhandledRejection' events as 'Unhandled rejection'", async () => {
(process as unknown as { emit: (e: string, ...args: unknown[]) => void }).emit(
'unhandledRejection',
new Error('rejected'),
Promise.resolve(),
);
await flushMicrotasks();

expect(requestHandler.postError).toHaveBeenCalled();
const payload = JSON.parse(postedJson as string);
expect(payload.attributes['error.type']).toBe('Unhandled rejection');
expect(payload.classifiers).toContain('UnhandledPromiseRejection');
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ export class UnhandledExceptionHandler implements ExceptionHandler {
new BacktraceReport(
rejection,
{
'error.type': 'Unhandled exception',
'error.type': 'Unhandled rejection',
unhandledPromiseRejectionId: id,
},
[],
Expand All @@ -71,7 +71,7 @@ export class UnhandledExceptionHandler implements ExceptionHandler {
new BacktraceReport(
rejection,
{
'error.type': 'Unhandled exception',
'error.type': 'Unhandled rejection',
unhandledPromiseRejectionId: id,
},
[],
Expand Down
67 changes: 67 additions & 0 deletions packages/react-native/tests/unhandledExceptionHandlerTests.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import { BacktraceReport } from '@backtrace/sdk-core';
import type { BacktraceClient } from '../src/BacktraceClient';

jest.mock('promise/setimmediate/rejection-tracking', () => ({
enable: jest.fn(),
}));

const mockHermesInternal: {
enablePromiseRejectionTracker?: jest.Mock;
hasPromise?: jest.Mock;
} = {};

jest.mock('../src/common/hermesHelper', () => ({
hermes: () => (mockHermesInternal.enablePromiseRejectionTracker ? mockHermesInternal : undefined),
}));

// eslint-disable-next-line @typescript-eslint/no-var-requires
const rejectionTracking = require('promise/setimmediate/rejection-tracking');

import { UnhandledExceptionHandler } from '../src/handlers/UnhandledExceptionHandler';

Comment thread
melekr marked this conversation as resolved.
describe('UnhandledExceptionHandler labeling', () => {
let sendMock: jest.Mock;
let client: BacktraceClient;
let handler: UnhandledExceptionHandler;

beforeEach(() => {
rejectionTracking.enable.mockClear();
delete mockHermesInternal.enablePromiseRejectionTracker;
delete mockHermesInternal.hasPromise;
sendMock = jest.fn();
client = { send: sendMock } as unknown as BacktraceClient;
handler = new UnhandledExceptionHandler();
});

it("Should tag captured unhandled promise rejections (non-Hermes) with error.type 'Unhandled rejection'", () => {
handler.captureUnhandledPromiseRejections(client);

expect(rejectionTracking.enable).toHaveBeenCalled();
const options = rejectionTracking.enable.mock.calls[0][0];
options.onUnhandled(42, new Error('Failed to fetch'));

expect(sendMock).toHaveBeenCalled();
const report = sendMock.mock.calls[0][0] as BacktraceReport;
expect(report.attributes['error.type']).toBe('Unhandled rejection');
expect(report.attributes['unhandledPromiseRejectionId']).toBe(42);
expect(report.classifiers).toContain('UnhandledPromiseRejection');
});

it("Should tag captured unhandled promise rejections (Hermes) with error.type 'Unhandled rejection'", () => {
mockHermesInternal.hasPromise = jest.fn().mockReturnValue(true);
mockHermesInternal.enablePromiseRejectionTracker = jest.fn();

handler.captureUnhandledPromiseRejections(client);

expect(mockHermesInternal.enablePromiseRejectionTracker).toHaveBeenCalled();
expect(rejectionTracking.enable).not.toHaveBeenCalled();
const options = mockHermesInternal.enablePromiseRejectionTracker.mock.calls[0][0];
options.onUnhandled(99, new Error('Failed to fetch'));

expect(sendMock).toHaveBeenCalled();
const report = sendMock.mock.calls[0][0] as BacktraceReport;
expect(report.attributes['error.type']).toBe('Unhandled rejection');
expect(report.attributes['unhandledPromiseRejectionId']).toBe(99);
expect(report.classifiers).toContain('UnhandledPromiseRejection');
});
});
9 changes: 8 additions & 1 deletion packages/sdk-core/src/model/report/BacktraceErrorType.ts
Original file line number Diff line number Diff line change
@@ -1 +1,8 @@
export type BacktraceErrorType = 'Message' | 'Exception' | 'Unhandled exception' | 'OOMException' | 'Hang' | 'Crash';
export type BacktraceErrorType =
| 'Message'
| 'Exception'
| 'Unhandled exception'
| 'Unhandled rejection'
| 'OOMException'
| 'Hang'
| 'Crash';
Loading