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

feat: reduce jserrors wrapping and remove onerror use #614

Merged
merged 2 commits into from
Jul 14, 2023
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
12 changes: 6 additions & 6 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion src/features/jserrors/aggregate/compute-stack-trace.js
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,7 @@ function computeStackTraceBySourceAndLine (ex) {
mode: 'sourceline',
name: className,
message: ex.message,
stackString: getClassName(ex) + ': ' + ex.message + '\n in evaluated code',
stackString: className + ': ' + ex.message + '\n in evaluated code',
frames: [{
func: 'evaluated code'
}]
Expand Down
36 changes: 0 additions & 36 deletions src/features/jserrors/instrument/debug.js

This file was deleted.

153 changes: 66 additions & 87 deletions src/features/jserrors/instrument/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,64 +5,55 @@

import { handle } from '../../../common/event-emitter/handle'
import { now } from '../../../common/timing/now'
import { getOrSet } from '../../../common/util/get-or-set'
import { wrapRaf, wrapTimer, wrapEvents, wrapXhr } from '../../../common/wrap'
import './debug'
import { InstrumentBase } from '../../utils/instrument-base'
import { FEATURE_NAME, NR_ERR_PROP } from '../constants'
import { FEATURE_NAME } from '../constants'
Copy link
Contributor

Choose a reason for hiding this comment

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

Can you remove NR_ERR_PROP from the constants file too?

import { FEATURE_NAMES } from '../../../loaders/features/features'
import { globalScope } from '../../../common/constants/runtime'
import { eventListenerOpts } from '../../../common/event-listener/event-listener-opts'
import { getRuntime } from '../../../common/config/config'
import { stringify } from '../../../common/util/stringify'
import { UncaughtError } from './uncaught-error'

export class Instrument extends InstrumentBase {
static featureName = FEATURE_NAME

#seenErrors = new Set()

Check warning on line 19 in src/features/jserrors/instrument/index.js

View check run for this annotation

Codecov / codecov/patch

src/features/jserrors/instrument/index.js#L19

Added line #L19 was not covered by tests

constructor (agentIdentifier, aggregator, auto = true) {
super(agentIdentifier, aggregator, FEATURE_NAME, auto)
// skipNext counter to keep track of uncaught
// errors that will be the same as caught errors.
this.skipNext = 0

try {
// this try-catch can be removed when IE11 is completely unsupported & gone
this.removeOnAbort = new AbortController()
} catch (e) {}

const thisInstrument = this
thisInstrument.ee.on('fn-start', function (args, obj, methodName) {
if (thisInstrument.abortHandler) thisInstrument.skipNext += 1
})
thisInstrument.ee.on('fn-err', function (args, obj, err) {
if (thisInstrument.abortHandler && !err[NR_ERR_PROP]) {
getOrSet(err, NR_ERR_PROP, function getVal () {
return true
})
this.thrown = true
handle('err', [err, now()], undefined, FEATURE_NAMES.jserrors, thisInstrument.ee)
}
})
thisInstrument.ee.on('fn-end', function () {
if (!thisInstrument.abortHandler) return
if (!this.thrown && thisInstrument.skipNext > 0) thisInstrument.skipNext -= 1
// Capture function errors early in case the spa feature is loaded
this.ee.on('fn-err', (args, obj, error) => {

Check warning on line 30 in src/features/jserrors/instrument/index.js

View check run for this annotation

Codecov / codecov/patch

src/features/jserrors/instrument/index.js#L30

Added line #L30 was not covered by tests
if (!this.abortHandler || this.#seenErrors.has(error)) return
this.#seenErrors.add(error)

Check warning on line 32 in src/features/jserrors/instrument/index.js

View check run for this annotation

Codecov / codecov/patch

src/features/jserrors/instrument/index.js#L32

Added line #L32 was not covered by tests

handle('err', [this.#castError(error), now()], undefined, FEATURE_NAMES.jserrors, this.ee)

Check warning on line 34 in src/features/jserrors/instrument/index.js

View check run for this annotation

Codecov / codecov/patch

src/features/jserrors/instrument/index.js#L34

Added line #L34 was not covered by tests
})
thisInstrument.ee.on('internal-error', function (e) {
handle('ierr', [e, now(), true], undefined, FEATURE_NAMES.jserrors, thisInstrument.ee)

this.ee.on('internal-error', (error) => {

Check warning on line 37 in src/features/jserrors/instrument/index.js

View check run for this annotation

Codecov / codecov/patch

src/features/jserrors/instrument/index.js#L37

Added line #L37 was not covered by tests
if (!this.abortHandler) return
handle('ierr', [this.#castError(error), now(), true], undefined, FEATURE_NAMES.jserrors, this.ee)

Check warning on line 39 in src/features/jserrors/instrument/index.js

View check run for this annotation

Codecov / codecov/patch

src/features/jserrors/instrument/index.js#L39

Added line #L39 was not covered by tests
})

// Replace global error handler with our own.
this.origOnerror = globalScope.onerror
globalScope.onerror = this.onerrorHandler.bind(this)
globalScope.addEventListener('unhandledrejection', (promiseRejectionEvent) => {

Check warning on line 42 in src/features/jserrors/instrument/index.js

View check run for this annotation

Codecov / codecov/patch

src/features/jserrors/instrument/index.js#L42

Added line #L42 was not covered by tests
if (!this.abortHandler) return

globalScope.addEventListener('unhandledrejection', (e) => {
/** rejections can contain data of any type -- this is an effort to keep the message human readable */
const err = castReasonToError(e.reason)
handle('err', [err, now(), false, { unhandledPromiseRejection: 1 }], undefined, FEATURE_NAMES.jserrors, this.ee)
handle('err', [this.#castPromiseRejectionEvent(promiseRejectionEvent), now(), false, { unhandledPromiseRejection: 1 }], undefined, FEATURE_NAMES.jserrors, this.ee)

Check warning on line 45 in src/features/jserrors/instrument/index.js

View check run for this annotation

Codecov / codecov/patch

src/features/jserrors/instrument/index.js#L45

Added line #L45 was not covered by tests
}, eventListenerOpts(false, this.removeOnAbort?.signal))

wrapRaf(this.ee)
wrapTimer(this.ee)
wrapEvents(this.ee)
if (getRuntime(agentIdentifier).xhrWrappable) wrapXhr(this.ee)
globalScope.addEventListener('error', (errorEvent) => {

Check warning on line 48 in src/features/jserrors/instrument/index.js

View check run for this annotation

Codecov / codecov/patch

src/features/jserrors/instrument/index.js#L48

Added line #L48 was not covered by tests
if (!this.abortHandler) return
if (this.#seenErrors.has(errorEvent.error)) {
this.#seenErrors.delete(errorEvent.error)
Copy link
Contributor

Choose a reason for hiding this comment

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

would you mind adding a comment or some here about the process behind this / why it's done? for others

return

Check warning on line 52 in src/features/jserrors/instrument/index.js

View check run for this annotation

Codecov / codecov/patch

src/features/jserrors/instrument/index.js#L51-L52

Added lines #L51 - L52 were not covered by tests
}

handle('err', [this.#castErrorEvent(errorEvent), now()], undefined, FEATURE_NAMES.jserrors, this.ee)

Check warning on line 55 in src/features/jserrors/instrument/index.js

View check run for this annotation

Codecov / codecov/patch

src/features/jserrors/instrument/index.js#L55

Added line #L55 was not covered by tests
}, eventListenerOpts(false, this.removeOnAbort?.signal))

this.abortHandler = this.#abort // we also use this as a flag to denote that the feature is active or on and handling errors
this.importAggregator()
Expand All @@ -71,67 +62,55 @@
/** Restoration and resource release tasks to be done if JS error loader is being aborted. Unwind changes to globals. */
#abort () {
this.removeOnAbort?.abort()
this.#seenErrors.clear()

Check warning on line 65 in src/features/jserrors/instrument/index.js

View check run for this annotation

Codecov / codecov/patch

src/features/jserrors/instrument/index.js#L65

Added line #L65 was not covered by tests
this.abortHandler = undefined // weakly allow this abort op to run only once
}

#castError (error) {
if (error instanceof Error) {
return error

Check warning on line 71 in src/features/jserrors/instrument/index.js

View check run for this annotation

Codecov / codecov/patch

src/features/jserrors/instrument/index.js#L71

Added line #L71 was not covered by tests
}

if (typeof error.message !== 'undefined') {
return new UncaughtError(error.message, error.filename, error.lineno, error.colno)

Check warning on line 75 in src/features/jserrors/instrument/index.js

View check run for this annotation

Codecov / codecov/patch

src/features/jserrors/instrument/index.js#L75

Added line #L75 was not covered by tests
}
Comment on lines +74 to +76
Copy link
Contributor

Choose a reason for hiding this comment

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

Is there a case when this is called with an error that's not an Error instance yet has a message?
I see fn-err and all internal-error events emitted with an actual error object from try-catch.

Copy link
Contributor

Choose a reason for hiding this comment

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

Likewise for castErrorEvent usage

Copy link
Contributor Author

Choose a reason for hiding this comment

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

throw can be passed any value.


return new UncaughtError(error)

Check warning on line 78 in src/features/jserrors/instrument/index.js

View check run for this annotation

Codecov / codecov/patch

src/features/jserrors/instrument/index.js#L78

Added line #L78 was not covered by tests
}

/**
* FF and Android browsers do not provide error info to the 'error' event callback,
* so we must use window.onerror
* @param {string} message
* @param {string} filename
* @param {number} lineno
* @param {number} column
* @param {Error | *} errorObj
* @returns
* Attempts to convert a PromiseRejectionEvent object to an Error object
* @param {PromiseRejectionEvent} unhandledRejectionEvent The unhandled promise rejection event
* @returns {Error} An Error object with the message as the casted reason
*/
onerrorHandler (message, filename, lineno, column, errorObj) {
if (typeof this.origOnerror === 'function') this.origOnerror(...arguments)

try {
if (this.skipNext) this.skipNext -= 1
else handle('err', [errorObj || new UncaughtException(message, filename, lineno), now()], undefined, FEATURE_NAMES.jserrors, this.ee)
} catch (e) {
#castPromiseRejectionEvent (promiseRejectionEvent) {
let prefix = 'Unhandled Promise Rejection: '

Check warning on line 87 in src/features/jserrors/instrument/index.js

View check run for this annotation

Codecov / codecov/patch

src/features/jserrors/instrument/index.js#L87

Added line #L87 was not covered by tests
if (promiseRejectionEvent?.reason instanceof Error) {
try {
handle('ierr', [e, now(), true], undefined, FEATURE_NAMES.jserrors, this.ee)
} catch (err) {
// do nothing
promiseRejectionEvent.reason.message = prefix + promiseRejectionEvent.reason.message
return promiseRejectionEvent.reason

Check warning on line 91 in src/features/jserrors/instrument/index.js

View check run for this annotation

Codecov / codecov/patch

src/features/jserrors/instrument/index.js#L90-L91

Added lines #L90 - L91 were not covered by tests
} catch (e) {
return promiseRejectionEvent.reason

Check warning on line 93 in src/features/jserrors/instrument/index.js

View check run for this annotation

Codecov / codecov/patch

src/features/jserrors/instrument/index.js#L93

Added line #L93 was not covered by tests
}
}
return false // maintain default behavior of the error event of Window
}
}

/**
*
* @param {string} message
* @param {string} filename
* @param {number} lineno
*/
function UncaughtException (message, filename, lineno) {
this.message = message || 'Uncaught error with no additional information'
this.sourceURL = filename
this.line = lineno
}

/**
* Attempts to cast an unhandledPromiseRejection reason (reject(...)) to an Error object
* @param {*} reason - The reason property from an unhandled promise rejection
* @returns {Error} - An Error object with the message as the casted reason
*/
function castReasonToError (reason) {
let prefix = 'Unhandled Promise Rejection: '
if (reason instanceof Error) {
if (typeof promiseRejectionEvent.reason === 'undefined') return new Error(prefix)
Copy link
Contributor

Choose a reason for hiding this comment

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

Should keep in mind that when we create a new Error, the stack trace is going to point back to this code (us), so users will likely first come to us saying there's some error being thrown in our code.

That said, if they call reject() in promise without an arg, should this be more descriptive than just the prefix string?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

This code was not changed, just moved. That said, I also questioned why we were creating new Error instances here for the same reason. I thought about changing this to use the UncaughtError class.

try {
reason.message = prefix + reason.message
return reason
return new Error(prefix + stringify(promiseRejectionEvent.reason))

Check warning on line 98 in src/features/jserrors/instrument/index.js

View check run for this annotation

Codecov / codecov/patch

src/features/jserrors/instrument/index.js#L98

Added line #L98 was not covered by tests
} catch (e) {
return reason
return new Error(promiseRejectionEvent.reason)

Check warning on line 100 in src/features/jserrors/instrument/index.js

View check run for this annotation

Codecov / codecov/patch

src/features/jserrors/instrument/index.js#L100

Added line #L100 was not covered by tests
}
}
if (typeof reason === 'undefined') return new Error(prefix)
try {
return new Error(prefix + stringify(reason))
} catch (err) {
return new Error(prefix)

/**
* Attempts to convert an ErrorEvent object to an Error object
* @param {ErrorEvent} errorEvent The error event
* @returns {Error|UncaughtError} The error event converted to an Error object
*/
#castErrorEvent (errorEvent) {
if (errorEvent.error instanceof Error) {
return errorEvent.error

Check warning on line 111 in src/features/jserrors/instrument/index.js

View check run for this annotation

Codecov / codecov/patch

src/features/jserrors/instrument/index.js#L111

Added line #L111 was not covered by tests
}

return new UncaughtError(errorEvent.message, errorEvent.filename, errorEvent.lineno, errorEvent.colno)

Check warning on line 114 in src/features/jserrors/instrument/index.js

View check run for this annotation

Codecov / codecov/patch

src/features/jserrors/instrument/index.js#L114

Added line #L114 was not covered by tests
}
}
15 changes: 15 additions & 0 deletions src/features/jserrors/instrument/uncaught-error.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
/**
* Represents an uncaught non Error type error. This class does
* not extend the Error class to prevent an invalid stack trace
* from being created. Use this class to cast thrown errors that
* do not use the Error class (strings, etc) to an object.
*/
export class UncaughtError {
constructor (message, filename, lineno, colno) {
this.name = 'UncaughtError'
cwli24 marked this conversation as resolved.
Show resolved Hide resolved
this.message = message
this.sourceURL = filename
this.line = lineno
this.column = colno

Check warning on line 13 in src/features/jserrors/instrument/uncaught-error.js

View check run for this annotation

Codecov / codecov/patch

src/features/jserrors/instrument/uncaught-error.js#L8-L13

Added lines #L8 - L13 were not covered by tests
}
}
2 changes: 1 addition & 1 deletion src/loaders/api/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@
try {
return cb.apply(this, arguments)
} catch (err) {
tracerEE.emit('fn-err', [arguments, this, typeof err == 'string' ? new Error(err) : err], contextStore)
tracerEE.emit('fn-err', [arguments, this, err], contextStore)

Check warning on line 130 in src/loaders/api/api.js

View check run for this annotation

Codecov / codecov/patch

src/loaders/api/api.js#L130

Added line #L130 was not covered by tests
// the error came from outside the agent, so don't swallow
throw err
} finally {
Expand Down
5 changes: 2 additions & 3 deletions tests/functional/err/uncaught.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,7 @@ testDriver.test('reporting uncaught errors', supported, function (t, browser, ro
const expectedErrorMessages = [
{ message: 'original onerror', tested: false },
{ message: 'uncaught error', tested: false },
{ message: 'fake', tested: false },
{ message: 'original return false', tested: false }
{ message: 'original return abc', tested: false }
]
actualErrors.forEach(err => {
const targetError = expectedErrorMessages.find(x => x.message === err.params.message)
Expand All @@ -43,7 +42,7 @@ testDriver.test('reporting uncaught errors', supported, function (t, browser, ro
if (err.params.message === 'fake') t.ok(err.params.exceptionClass !== 'Error', `fake error has correct exceptionClass (${err.params.exceptionClass})`)
else t.ok(err.params.exceptionClass === 'Error', `error has correct exceptionClass (${err.params.exceptionClass})`)
})
t.ok(expectedErrorMessages.every(x => x.tested), 'All expected error messages were found')
t.ok(expectedErrorMessages.every(x => x.tested), `All expected error messages were found ${JSON.stringify(expectedErrorMessages.filter(x => !x.tested))}`)
t.end()
}).catch(fail)

Expand Down
2 changes: 1 addition & 1 deletion tests/functional/err/unhandled-rejection-readable.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ testDriver.test('unhandledPromiseRejections are caught and are readable', suppor
t.ok(!!err.params.stack_trace, 'stack_trace exists')
t.ok(!!err.params.stackHash, 'stackHash exists')
})
t.ok(expectedErrorMessages.every(x => x.tested), `All expected error messages were found ${expectedErrorMessages.filter(x => !x.tested)}`)
t.ok(expectedErrorMessages.every(x => x.tested), `All expected error messages were found ${JSON.stringify(expectedErrorMessages.filter(x => !x.tested))}`)
t.end()
}).catch(fail)

Expand Down
7 changes: 2 additions & 5 deletions tests/functional/spa/errors.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -160,9 +160,6 @@ testDriver.test('error in custom tracer', function (t, browser, router) {
})

testDriver.test('string error in custom tracer', function (t, browser, router) {
// This tests throwing a string inside a custom tracer. It shows that in a specific case, the
// agent will double count the error because the error is first caught in the custom node, re-thrown, and caught again in the click event listener.
// This behavior only happens in ie11, other browsers ignore the string error and only generate 1 error.
waitForPageLoadAnInitialCalls(browser, router, 'spa/errors/captured-custom-string.html')
.then(() => {
return clickPageAndWaitForEventsAndErrors(t, browser, router)
Expand All @@ -171,8 +168,7 @@ testDriver.test('string error in custom tracer', function (t, browser, router) {
// check that errors payload did not include the error
const errors = getErrorsFromResponse(errorData, browser)

if (browser.match('ie@>=11')) t.equal(errors.length, 2, 'should have 2 errors (1 String Class, 1 Error Class)')
else t.equal(errors.length, 1, 'should have 1 errors')
t.equal(errors.length, 1, 'should have 1 errors')

let { body, query } = eventData
let interactionTree = (body && body.length ? body : querypack.decode(query.e))[0]
Expand All @@ -183,6 +179,7 @@ testDriver.test('string error in custom tracer', function (t, browser, router) {
var nodeId = interactionTree.children[0].nodeId

var error = errors[0]
console.log(JSON.stringify(error))
Copy link
Contributor

Choose a reason for hiding this comment

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

remnant

t.equal(error.params.message, 'some error')
t.equal(error.params.browserInteractionId, interactionId, 'should have the correct interaction id')
t.equal(error.params.parentNodeId, nodeId, 'has the correct node id')
Expand Down
2 changes: 1 addition & 1 deletion tools/test-builds/browser-agent-wrapper/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,6 @@
"author": "",
"license": "ISC",
"dependencies": {
"@newrelic/browser-agent": "file:../../../temp/newrelic-browser-agent-1.235.0.tgz"
"@newrelic/browser-agent": "file:../../../temp/newrelic-browser-agent-1.236.0.tgz"
}
}
2 changes: 1 addition & 1 deletion tools/test-builds/browser-tests/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,6 @@
"author": "",
"license": "ISC",
"dependencies": {
"@newrelic/browser-agent": "file:../../../temp/newrelic-browser-agent-1.235.0.tgz"
"@newrelic/browser-agent": "file:../../../temp/newrelic-browser-agent-1.236.0.tgz"
}
}
2 changes: 1 addition & 1 deletion tools/test-builds/raw-src-wrapper/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,6 @@
"author": "",
"license": "ISC",
"dependencies": {
"@newrelic/browser-agent": "file:../../../temp/newrelic-browser-agent-1.235.0.tgz"
"@newrelic/browser-agent": "file:../../../temp/newrelic-browser-agent-1.236.0.tgz"
}
}
2 changes: 1 addition & 1 deletion tools/test-builds/vite-react-wrapper/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"main": "index.js",
"license": "MIT",
"dependencies": {
"@newrelic/browser-agent": "file:../../../temp/newrelic-browser-agent-1.235.0.tgz",
"@newrelic/browser-agent": "file:../../../temp/newrelic-browser-agent-1.236.0.tgz",
"react": "18.2.0",
"react-dom": "18.2.0"
},
Expand Down
Loading