Skip to content
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

[RUM] Catch errors thrown by user callbacks #745

Merged
merged 17 commits into from
Feb 25, 2021
Merged
Show file tree
Hide file tree
Changes from 5 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: 5 additions & 1 deletion packages/core/src/boot/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { areCookiesAuthorized, CookieOptions } from '../browser/cookie'
import { buildConfiguration, UserConfiguration } from '../domain/configuration'
import { setDebugMode, startInternalMonitoring } from '../domain/internalMonitoring'
import { Datacenter } from '../domain/transportConfiguration'
import { catchErrors } from '../tools/catchErrors'

export function makePublicApi<T>(stub: T): T & { onReady(callback: () => void): void } {
const publicApi = {
Expand Down Expand Up @@ -31,7 +32,7 @@ export function defineGlobal<Global, Name extends keyof Global>(global: Global,
const existingGlobalVariable: { q?: Array<() => void> } | undefined = global[name]
global[name] = api
if (existingGlobalVariable && existingGlobalVariable.q) {
existingGlobalVariable.q.forEach((fn) => fn())
existingGlobalVariable.q.forEach((fn) => catchErrors(fn, 'Error thrown during SDK initialization:')())
webNeat marked this conversation as resolved.
Show resolved Hide resolved
bcaudan marked this conversation as resolved.
Show resolved Hide resolved
}
}

Expand All @@ -48,6 +49,9 @@ export interface BuildEnv {
}

export function commonInit(userConfiguration: UserConfiguration, buildEnv: BuildEnv) {
if (userConfiguration.beforeSend) {
userConfiguration.beforeSend = catchErrors(userConfiguration.beforeSend, 'beforeSend threw an error:')
}
bcaudan marked this conversation as resolved.
Show resolved Hide resolved
const configuration = buildConfiguration(userConfiguration, buildEnv)
const internalMonitoring = startInternalMonitoring(configuration)

Expand Down
1 change: 1 addition & 0 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ export {
resetFetchProxy,
} from './browser/fetchProxy'
export { BoundedBuffer } from './tools/boundedBuffer'
export { catchErrors } from './tools/catchErrors'
export { createContextManager } from './tools/contextManager'
export { limitModification } from './tools/limitModification'

Expand Down
18 changes: 18 additions & 0 deletions packages/core/src/tools/catchErrors.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { catchErrors } from './catchErrors'

describe('catchErrors', () => {
it('returns the same result as the original function', () => {
const wrappedFn = catchErrors((a: number, b: number) => a + b, 'Error during callback')
expect(wrappedFn(10, 2)).toBe(12)
})

it('logs errors using console.error and returns undefined', () => {
const consoleErrorSpy = spyOn(console, 'error')
const myError = 'Ooops!'
const wrappedFn = catchErrors(() => {
throw myError
}, 'Error during callback')
expect(wrappedFn()).toBe(undefined)
expect(consoleErrorSpy).toHaveBeenCalledWith('Error during callback', myError)
})
})
11 changes: 11 additions & 0 deletions packages/core/src/tools/catchErrors.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
export function catchErrors<Args extends any[], R>(fn: (...args: Args) => R, errorMsg: string) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would rename it to catchUserErrors to make it a bit clearer

return (...args: Args) => {
let result
try {
result = fn(...args)
} catch (err) {
console.error(errorMsg, err)
}
return result
}
}
17 changes: 0 additions & 17 deletions packages/core/src/tools/limitModification.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,21 +92,4 @@ describe('limitModification', () => {
foo: { bar: 'qux' },
})
})

it('should catch and log modifier exception', () => {
const object = { foo: { bar: 'bar' }, qux: 'qux' }
const modifier = (candidate: any) => {
candidate.qux = 'modified'
candidate.foo.qux.bar = 'will throw'
}
const errorSpy = spyOn(console, 'error')

limitModification(object, ['foo.bar', 'qux'], modifier)

expect(errorSpy).toHaveBeenCalled()
expect(object).toEqual({
foo: { bar: 'bar' },
qux: 'qux',
})
})
})
8 changes: 1 addition & 7 deletions packages/core/src/tools/limitModification.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,7 @@ export function limitModification<T extends Context, Result>(
modifier: (object: T) => Result
): Result | undefined {
const clone = deepClone(object)
let result
try {
result = modifier(clone)
} catch (e) {
console.error(e)
return
}
const result = modifier(clone)
modifiableFieldPaths.forEach((path) => {
const originalValue = get(object, path)
const newValue = get(clone, path)
Expand Down
25 changes: 11 additions & 14 deletions packages/rum-core/src/domain/rumEventsCollection/view/trackViews.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,13 @@
import { addEventListener, DOM_EVENT, generateUUID, monitor, noop, ONE_MINUTE, throttle } from '@datadog/browser-core'
import {
addEventListener,
catchErrors,
DOM_EVENT,
generateUUID,
monitor,
noop,
ONE_MINUTE,
throttle,
} from '@datadog/browser-core'
import { NewLocationListener } from '../../../boot/rum'

import { supportPerformanceTimingEvent } from '../../../browser/performanceCollection'
Expand Down Expand Up @@ -41,7 +50,7 @@ export function trackViews(
lifeCycle: LifeCycle,
onNewLocation: NewLocationListener = () => undefined
) {
onNewLocation = wrapOnNewLocation(onNewLocation)
onNewLocation = catchErrors(onNewLocation, 'onNewLocation threw an error:')
bcaudan marked this conversation as resolved.
Show resolved Hide resolved
const startOrigin = 0
const initialView = newView(
lifeCycle,
Expand Down Expand Up @@ -345,15 +354,3 @@ function sanitizeTiming(name: string) {
}
return sanitized
}

function wrapOnNewLocation(onNewLocation: NewLocationListener): NewLocationListener {
return (newLocation, oldLocation) => {
let result
try {
result = onNewLocation(newLocation, oldLocation)
} catch (err) {
console.error('onNewLocation threw an error:', err)
}
return result
}
}