Skip to content

feat(core): Extract errors from props in unkown inputs #11526

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 2 commits into from
Apr 12, 2024
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
59 changes: 39 additions & 20 deletions packages/browser/src/eventbuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,7 @@ export function exceptionFromError(stackParser: StackParser, ex: Error): Excepti
return exception;
}

/**
* @hidden
*/
export function eventFromPlainObject(
function eventFromPlainObject(
stackParser: StackParser,
exception: Record<string, unknown>,
syntheticException?: Error,
Expand All @@ -60,35 +57,46 @@ export function eventFromPlainObject(
const client = getClient();
const normalizeDepth = client && client.getOptions().normalizeDepth;

const event: Event = {
// If we can, we extract an exception from the object properties
const errorFromProp = getErrorPropertyFromObject(exception);

const extra = {
__serialized__: normalizeToSize(exception, normalizeDepth),
};

if (errorFromProp) {
return {
exception: {
values: [exceptionFromError(stackParser, errorFromProp)],
},
extra,
};
}

const event = {
exception: {
values: [
{
type: isEvent(exception) ? exception.constructor.name : isUnhandledRejection ? 'UnhandledRejection' : 'Error',
value: getNonErrorObjectExceptionValue(exception, { isUnhandledRejection }),
},
} as Exception,
],
},
extra: {
__serialized__: normalizeToSize(exception, normalizeDepth),
},
};
extra,
} satisfies Event;

if (syntheticException) {
const frames = parseStackFrames(stackParser, syntheticException);
if (frames.length) {
// event.exception.values[0] has been set above
(event.exception as { values: Exception[] }).values[0].stacktrace = { frames };
event.exception.values[0].stacktrace = { frames };
}
}

return event;
}

/**
* @hidden
*/
export function eventFromError(stackParser: StackParser, ex: Error): Event {
function eventFromError(stackParser: StackParser, ex: Error): Event {
return {
exception: {
values: [exceptionFromError(stackParser, ex)],
Expand All @@ -97,7 +105,7 @@ export function eventFromError(stackParser: StackParser, ex: Error): Event {
}

/** Parses stack frames from an error */
export function parseStackFrames(
function parseStackFrames(
stackParser: StackParser,
ex: Error & { framesToPop?: number; stacktrace?: string },
): StackFrame[] {
Expand Down Expand Up @@ -283,10 +291,7 @@ export function eventFromUnknownInput(
return event;
}

/**
* @hidden
*/
export function eventFromString(
function eventFromString(
stackParser: StackParser,
message: ParameterizedString,
syntheticException?: Error,
Expand Down Expand Up @@ -346,3 +351,17 @@ function getObjectClassName(obj: unknown): string | undefined | void {
// ignore errors here
}
}

/** If a plain object has a property that is an `Error`, return this error. */
function getErrorPropertyFromObject(obj: Record<string, unknown>): Error | undefined {
for (const prop in obj) {
if (Object.prototype.hasOwnProperty.call(obj, prop)) {
const value = obj[prop];
if (value instanceof Error) {
return value;
}
}
}

return undefined;
}
124 changes: 102 additions & 22 deletions packages/browser/test/unit/eventbuilder.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { defaultStackParser } from '../../src';
import { eventFromPlainObject } from '../../src/eventbuilder';
import { eventFromUnknownInput } from '../../src/eventbuilder';

jest.mock('@sentry/core', () => {
const original = jest.requireActual('@sentry/core');
Expand All @@ -12,17 +12,6 @@ jest.mock('@sentry/core', () => {
},
};
},
getCurrentHub() {
return {
getClient(): any {
return {
getOptions(): any {
return { normalizeDepth: 6 };
},
};
},
};
},
};
});

Expand All @@ -35,7 +24,7 @@ afterEach(() => {
jest.resetAllMocks();
});

describe('eventFromPlainObject', () => {
describe('eventFromUnknownInput', () => {
it('should use normalizeDepth from init options', () => {
const deepObject = {
a: {
Expand All @@ -53,7 +42,7 @@ describe('eventFromPlainObject', () => {
},
};

const event = eventFromPlainObject(defaultStackParser, deepObject);
const event = eventFromUnknownInput(defaultStackParser, deepObject);

expect(event?.extra?.__serialized__).toEqual({
a: {
Expand All @@ -71,16 +60,107 @@ describe('eventFromPlainObject', () => {
});

it.each([
['empty object', {}, 'Object captured as exception with keys: [object has no keys]'],
['pojo', { prop1: 'hello', prop2: 2 }, 'Object captured as exception with keys: prop1, prop2'],
['Custom Class', new MyTestClass(), 'Object captured as exception with keys: prop1, prop2'],
['Event', new Event('custom'), 'Event `Event` (type=custom) captured as exception'],
['MouseEvent', new MouseEvent('click'), 'Event `MouseEvent` (type=click) captured as exception'],
] as [string, Record<string, unknown>, string][])(
['empty object', {}, {}, 'Object captured as exception with keys: [object has no keys]'],
[
'pojo',
{ prop1: 'hello', prop2: 2 },
{ prop1: 'hello', prop2: 2 },
'Object captured as exception with keys: prop1, prop2',
],
[
'Custom Class',
new MyTestClass(),
{ prop1: 'hello', prop2: 2 },
'Object captured as exception with keys: prop1, prop2',
],
[
'Event',
new Event('custom'),
{
currentTarget: '[object Null]',
isTrusted: false,
target: '[object Null]',
type: 'custom',
},
'Event `Event` (type=custom) captured as exception',
],
[
'MouseEvent',
new MouseEvent('click'),
{
currentTarget: '[object Null]',
isTrusted: false,
target: '[object Null]',
type: 'click',
},
'Event `MouseEvent` (type=click) captured as exception',
],
] as [string, Record<string, unknown>, Record<string, unknown>, string][])(
'has correct exception value for %s',
(_name, exception, expected) => {
const actual = eventFromPlainObject(defaultStackParser, exception);
(_name, exception, serializedException, expected) => {
const actual = eventFromUnknownInput(defaultStackParser, exception);
expect(actual.exception?.values?.[0]?.value).toEqual(expected);

expect(actual.extra).toEqual({
__serialized__: serializedException,
});
},
);

it('handles object with error prop', () => {
const error = new Error('Some error');
const event = eventFromUnknownInput(defaultStackParser, {
foo: { bar: 'baz' },
name: 'BadType',
err: error,
});

expect(event.exception?.values?.[0]).toEqual(
expect.objectContaining({
mechanism: { handled: true, synthetic: true, type: 'generic' },
type: 'Error',
value: 'Some error',
}),
);
expect(event.extra).toEqual({
__serialized__: {
foo: { bar: 'baz' },
name: 'BadType',
err: {
message: 'Some error',
name: 'Error',
stack: expect.stringContaining('Error: Some error'),
},
},
});
});

it('handles class with error prop', () => {
const error = new Error('Some error');

class MyTestClass {
prop1 = 'hello';
prop2 = error;
}

const event = eventFromUnknownInput(defaultStackParser, new MyTestClass());

expect(event.exception?.values?.[0]).toEqual(
expect.objectContaining({
mechanism: { handled: true, synthetic: true, type: 'generic' },
type: 'Error',
value: 'Some error',
}),
);
expect(event.extra).toEqual({
__serialized__: {
prop1: 'hello',
prop2: {
message: 'Some error',
name: 'Error',
stack: expect.stringContaining('Error: Some error'),
},
},
});
});
});
Loading