简体   繁体   中英

How to chain Q promise with previous errors on finally()

I am wondering how to chain errors on Q using finally.

Consider following code

function p1() {
    throw new Error("p1 error");
}

function p2() {
    throw new Error("p2 error");
}

function p3() {
    return Q.fcall(p1)
        .finally(function () {
            return Q.fcall(p2);
        }); 
}

p3()
    .done();

The Error with message "p1 error" is lost since it was override by Error "p2 error". How can I throw all the errors (or combine the errors)?

Currently, I am working on a socket connection on nodejs. I am using .finally() to close the socket after each connection.

However, errors (eg: authentication error) before .finally() will be overriden by one in .finally() (eg: connection close error). So, I am wondering how to get all errors

Thanks

You could do something like this:

function p3() {
    return Q.fcall(p1)
    .finally(function(p) {
        return Q.fcall(p2).catch(function(e) {
            if (!p.isRejected()) throw e;
            var agg = new Error("multiple errors occured");
            agg[0] = p.inspect().reason;
            agg[1] = e;
            agg.length = 2;
            throw agg;
        });
    }); 
}

(based on Bluebird's AggregateError )

Of course it is tedious, but I can't imagine something better.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM