Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you "plug in" to unhandled Promise rejections in Chrome? [duplicate]

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.

like image 415
Michelle Tilley Avatar asked Sep 25 '15 18:09

Michelle Tilley


1 Answers

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.

like image 115
ilyaigpetrov Avatar answered Sep 28 '22 06:09

ilyaigpetrov