Last Updated: February 25, 2016
·
907
· frosas

Keep track of unhandled rejected Q promises

There's a rule in Q (and other promise libs implementing .done()) that avoids a lot of debugging frustration:

The Golden Rule of done vs. then usage is: either return your promise to
someone else, or if the chain ends with you, call done to terminate it.

After some practice it's easy and natural to follow it but, as any other manual task, it's still error-prone.

Thankfully Q keeps tracks of the unhandled failed promises so we have the chance to do something with them. Because a promise can be handled long after being created, there's only one moment when we know for sure a promise was unhandled: when the page unloads.

With this in mind, for example, we can throw the first unhandled error in the event loop so this would be handled like any other error being thrown outside of a promise:

// Throw the first unhandled rejected Q promise
window.addEventListener('beforeunload', function () {
    Q.getUnhandledReasons().forEach(function (error) {
        throw error;
    });
});

Usually by default the browser will show the error in the console, but you can do whatever you want by overriding window.onerror.

Extra notes

  • alert doesn't work during unload, use event.returnValue = 'message'
  • Ajax requests have to be synchronous to ensure they are executed. For example, Bugsnag seems to track errors being thrown during unload but Sentry doesn't.