Catching errors generated in Promises within Promises in JavaScript

狂风中的少年 提交于 2019-12-12 15:18:38

问题


Is it possible to have errors bubble up in Promises?

See the code below for reference, I'd like to get promise1.catch to catch the error generated in promise2 (which current does not work with this code):

function test() {
    var promise1 = new Promise(function(resolve1) {
        var promise2 = new Promise(function(resolve2) {
            throw new Error('Error in promise2!');
        });

        promise2.catch(function(error2) {
            console.log('Caught at error2', error2);
        });
    });

    promise1.catch(function(error1) {
        console.log('Caught at error1', error1);
    });
}

test();

回答1:


Yes!!

Error propagation in promises is one of its strongest suits. It acts exactly like in synchronous code.

try { 
    throw new Error("Hello");
} catch (e){
    console.log('Caught here, when you catch an error it is handled');
}

Is very similar to:

Promise.try(function(){
    throw new Error("Hello");
}).catch(function(e){
    console.log('Caught here, when you catch an error it is handled');
});

Just like in sequential code, if you want to do some logic to the error but not mark it as handled - you rethrow it:

try { 
   throw new Error("Hello");
} catch (e){
    console.log('Caught here, when you catch an error it is handled');
    throw e; // mark the code as in exceptional state
}

Which becomes:

var p = Promise.try(function(){
   throw new Error("Hello");
}).catch(function(e){
    console.log('Caught here, when you catch an error it is handled');
    throw e; // mark the promise as still rejected, after handling it.
});

p.catch(function(e){
     // handle the exception
});

Note that in Bluebird you can have typed and conditional catches, so if all you're doing is an if on the type or contents of the promise to decide whether or not to handle it - you can save that.

var p = Promise.try(function(){
   throw new IOError("Hello");
}).catch(IOError, function(e){
    console.log('Only handle IOError, do not handle syntax errors');
});

You can also use .error to handle OperationalErrors which originate in promisified APIs. In general OperationalError signifies an error you can recover from (vs a programmer error). For example:

var p = Promise.try(function(){
   throw new Promise.OperationalError("Lol");
}).error(function(e){
    console.log('Only handle operational errors');
});

This has the advantage of not silencing TypeErrors or syntax errors in your code, which can be annoying in JavaScript.



来源:https://stackoverflow.com/questions/25035019/catching-errors-generated-in-promises-within-promises-in-javascript

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