Reporting JavaScript Errors To New Relic
With New Relic configured properly, unhandled exceptions will be handled and recorded by New Relic automatically. If you want to record a error manually while allowing your code to continue to execute, you can build a quick utility function.
Utility Function #
// src/utils.js
/**
* Log an instance of an Error to New Relic.
* @param error Error - The error to log.
* @returns undefined
*/
const logErrorEvent = (error) => {
if (
error instanceof Error &&
window.newrelic &&
typeof window.newrelic.noticeError === 'function'
) {
window.newrelic.noticeError(error);
}
};
export { logErrorEvent };
The if
in this function checks to make sure:
- Is the argument to
error
an instance of theError
class? - Is
window.newrelic
defined? - Is
window.newrelic.noticeError
defined & is it afunction
?
Usage #
import { logErrorEvent } from './src/utils';
fetch('https://example.com')
.then(response => response.json())
.then(json => {
if (json.error.code) {
logErrorEvent(new Error(json.error.code))
}
})
.catch(error => logErrorEvent(error);
- Previous: Testing Stimulus With Jest
- Next: Find or Create By (Rails)