Promises and generic .catch() statements

蹲街弑〆低调 提交于 2019-11-30 02:46:15

问题


I'm writing an API for my system, that's sending an XHR to the server and returns a promise that should be handled by the caller - so far so good.

For each API call I must use a .then and .catch calls, but usually (like 75% of the time) the .catch references the same functionality which simply prints using console.error.

My question is - Is there a way to attach a default catch statement for each promise that I create? (that let's say prints to the console), and for each promise that I would like to further handle the rejection, I would add another .catch call (or even override it)?

Simplified example where each call has its own .catch: http://jsbin.com/waqufapide/edit?js,console

Non working version that tries to implement the desired behavior: http://jsbin.com/nogidugiso/2/edit?js,console

In the second example, instead of just returning deferred.promise, I return a promise with an attached catch() handler:

return deferred.promise.catch(function (error) {
  console.error(error);
});

Both then catch and then functions are called in that case.

I do realize the Q exposes the getUnhandledReasons() function and onerror event, but I don't really want to use .done() for each promise nor build some kind of timer/interval to handle list of un-handled rejections.

Other libraries such as bluebird expose onPossiblyUnhandledRejection events, which I have to admit is a bit nicer solution, but still not quite what I'm looking for.


回答1:


I think all you want to do is rethrow the exception after you've logged it so other handlers will deal with it properly:

return deferred.promise.catch(function (error) {
  console.error(error);
  throw e; // rethrow the promise
});



回答2:


Q use NodeJS process to raise unhandledRejection. If you dont use NodeJS, you can use this Workaround:

// Simulating NodeJS process.emit to handle Q exceptions globally
process = {
    emit: function (event, reason, promise) {
        switch(event)
        {
            case 'unhandledRejection':
                console.error("EXCEPTION-Q> %s", reason.stack || reason)
                break;
        }
    }
}



回答3:


With bluebird Promises, you can call

Promise.onPossiblyUnhandledRejection(function(error){
    // Handle error here
    console.error(error);
});

With iojs you have the process.on('unhandledRejection') handler as specified here. (Also worth reading this and this

As far as I know, neither native Promises anywhere else nor Q Promises offer this functionality.



来源:https://stackoverflow.com/questions/31354656/promises-and-generic-catch-statements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!