10

A while back, v8 gained the capability to detect Promises that are rejected but have no handlers attached (commit). This landed in Chrome as a nice console error, especially useful for when you've made a typo or forget to attach a handler:

Example of Chrome reporting a rejected promise with handlers

I would like to add a handler to take some action (e.g., reporting to an error reporting service) when this happens, similar to the uncaught exception pattern:

window.addEventListener("error", handler);

Alternatively, I'm looking for any mechanism that I can use to automatically invoke some sort of callback when a promise is rejected but not handled on that tick.

Michelle Tilley
  • 157,729
  • 40
  • 374
  • 311
  • 3
    Try ``window.addEventListener("unhandledrejection", function(e) {});`` Good info here: https://github.com/petkaantonov/bluebird/blob/master/API.md#global-rejection-events – Jeff Sep 25 '15 at 20:21
  • @Jeff These are plain ol' native Promises as specified by ES2015 and implemented in v8. – Michelle Tilley Sep 25 '15 at 20:24
  • 3
    @BinaryMuse: https://github.com/domenic/unhandled-rejections-browser-spec. Those events are going to become standard, and will be supported in Chrome as well. – Bergi Sep 28 '15 at 20:51
  • If you add a `catch()` at the end of the promises chain, won't you get what you need? – Supersharp Oct 05 '15 at 13:30
  • I wonder if we shouldn't consider dupe-closing in the other direction instead—this one seems better to me, and has more visibility. – Air Oct 06 '15 at 23:43

1 Answers1

2

Until window.addEventListener('unhandledrejection', e => ...) is here you may hack your own Promise constructor which creates original Promise and calls catch on it passing:

error => {
  var errorEvent = new ErrorEvent('error', {
    message: error.message,
    error: error
  });
  window.dispatchEvent(errorEvent); // For error listeners.
  throw error; // I prefer to see errors on the console.
}

But it seems we have to patch then, catch and Promise.reject also -- lots of work.

Someone may want to write a polyfill to emit custom unhandledrejection event in such cases.

ilyaigpetrov
  • 3,657
  • 3
  • 30
  • 46