Skip to content

Commit 89380eb

Browse files
authored
fix(integrations): capture exception if any arg to console method is an error (#8671)
This PR adds support for capturing an exception for the any error in a console method call (only the first error instance), not just if the first argument is an error. This is a problem for us because timestamps are always the first argument in console calls and we often add a context message before the error.
1 parent a57e6c2 commit 89380eb

File tree

2 files changed

+17
-2
lines changed

2 files changed

+17
-2
lines changed

packages/integrations/src/captureconsole.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -55,14 +55,15 @@ export class CaptureConsole implements Integration {
5555
});
5656

5757
let message = safeJoin(args, ' ');
58+
const error = args.find(arg => arg instanceof Error);
5859
if (level === 'assert') {
5960
if (args[0] === false) {
6061
message = `Assertion failed: ${safeJoin(args.slice(1), ' ') || 'console.assert'}`;
6162
scope.setExtra('arguments', args.slice(1));
6263
hub.captureMessage(message);
6364
}
64-
} else if (level === 'error' && args[0] instanceof Error) {
65-
hub.captureException(args[0]);
65+
} else if (level === 'error' && error) {
66+
hub.captureException(error);
6667
} else {
6768
hub.captureMessage(message);
6869
}

packages/integrations/test/captureconsole.test.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -243,6 +243,20 @@ describe('CaptureConsole setup', () => {
243243
expect(mockHub.captureException).toHaveBeenCalledWith(someError);
244244
});
245245

246+
it('should capture exception when console logs an error object in any of the args when level set to "error"', () => {
247+
const captureConsoleIntegration = new CaptureConsole({ levels: ['error'] });
248+
captureConsoleIntegration.setupOnce(
249+
() => undefined,
250+
() => getMockHubWithIntegration(captureConsoleIntegration),
251+
);
252+
253+
const someError = new Error('some error');
254+
global.console.error('Something went wrong', someError);
255+
256+
expect(mockHub.captureException).toHaveBeenCalledTimes(1);
257+
expect(mockHub.captureException).toHaveBeenCalledWith(someError);
258+
});
259+
246260
it('should capture message on `console.log` when no levels are provided in constructor', () => {
247261
const captureConsoleIntegration = new CaptureConsole();
248262
captureConsoleIntegration.setupOnce(

0 commit comments

Comments
 (0)