Search code examples
javascriptpromiseqes6-promiseglobalevent

How can I trigger global onError handler via native Promise when runtime error occurs?


With Q.js I can trigger window.onerror using .done():

window.onerror = function() {
    console.log('error from handler');
}
var q = Q('initValue').then(function (data) {
    throw new Error("Can't do something and use promise.catch method.");
});
q.catch(function(error){
    throw new Error("This last exception will trigger window.onerror handler via done method.");
})
.done();

In native Promise (ES6) we have no .done(), and last ".catch" is the end of chain:

var p = new Promise(function () {
    throw new Error("fail");
});
p.catch(function (error) {
    throw new Error("Last exception in last chain link");
});

"throw new Error(...)" in ".catch" is one of the simplest way to reproduce runtime error. In reality, it may be another analog of runtime error (EvalError, SyntaxError, TypeError, etc.), e.g.:

var a = [];
a(); // Uncaught TypeError: a is not a function

.done usage is an example to explain my target more detail. I haven't a goal to duplicate .done API.

My task is: I have a promises chain and handler on window.onerror. All errors inside chain I can handle by .cath, except runtime error at the end of the chain. When any runtime exception occurs at the end of promise's methods chain, I need to have the triggered handler that was hanged on window.onerror.

The restrictions: only native JS, must use window.onerror.

What is the best way to trigger this global handler via native Promise?


Solution

  • Throw the error asynchronously:

    window.addEventListener('error', function() {
      console.log('error from handler');
    });
    new Promise(function () {
      throw new Error("fail");
    }).catch(function (error) {
      setTimeout(() => {throw new Error("Last exception in last chain link")}, 0);
    });