Skip to content

Instantly share code, notes, and snippets.

@micahjon
Last active October 22, 2021 20:27
Show Gist options
  • Save micahjon/b710f85718cd71b01658d6e5d75bd55a to your computer and use it in GitHub Desktop.
Save micahjon/b710f85718cd71b01658d6e5d75bd55a to your computer and use it in GitHub Desktop.
Queue errors and replay when Sentry JS SDK loads
/* eslint-disable prefer-spread, prefer-rest-params, no-console */
/**
* Queue up Sentry.* method calls, thrown errors, and unhandled Promise rejections and
* replay them as soon as Sentry JS SDK has loaded
*
* Minify & inline this script before any other JS in the <head>
*
* Remember to add onload="onSentryLoad()" to your asynchronously loaded Sentry script, e.g.
* <script defer src="https://.../sentry-1.13.3.min.js" onload="onSentryLoad()"><script>
*/
(function () {
window.Sentry = {};
const queue = [];
// Queue up method calls
// (optional, only needed if you want to call them before Sentry loads)
['addBreadcrumb', 'captureException', 'configureScope', 'withScope'].forEach((methodName) => {
Sentry[methodName] = function () {
queue.push({ methodName, args: arguments });
};
});
// Queue up errors
window.addEventListener('error', handleErrorEvent);
function handleErrorEvent({ error }) {
if (error) queue.push({ errorObject: error });
}
// Queue up Promise rejections
window.addEventListener('unhandledrejection', handleProjectRejectionEvent);
function handleProjectRejectionEvent(event) {
queue.push({ promiseEvent: event });
}
// This function is called when Sentry JS SDK loads
// Remember to add onload="onSentryLoad()" to the <script>
window.onSentryLoad = function() {
// Stop queueing errors & unhandled Promise rejections
// Sentry will take care of overwriting each of the methods (e.g. addBreadcrumb)
window.removeEventListener('error', handleErrorEvent);
window.removeEventListener('unhandledrejection', handleProjectRejectionEvent);
// Initialize Sentry
Sentry.init(getSentryConfig());
// Replay method calls
for (let i = 0; i < queue.length; i++) {
const { methodName, args } = queue[i];
if (methodName) {
// console.log('>> Replay method', methodName, queue[i]);
Sentry[methodName].apply(Sentry, args);
}
}
// Replay error and unhandled Promise rejections
for (let i = 0; i < queue.length; i++) {
const { errorObject, promiseEvent } = queue[i];
if (errorObject) {
console.log('Replay error for Sentry');
Sentry.captureException(errorObject);
} else if (promiseEvent) {
console.log('Replay promise rejection for Sentry');
window.onunhandledrejection(promiseEvent);
}
}
};
function getSentryConfig() {
// Stick your Sentry configuration here...
return {
dsn: '..YOUR DSN HERE.',
// etc...
};
}
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment