捕获JavaScript中的Promises中的Promises中生成的错误

Kir*_*met 3 javascript error-handling node.js promise bluebird

是否有可能在Promises中出现错误?

请参阅下面的代码以供参考,我想promise1.catch捕获生成的错误promise2(当前这个代码不起作用):

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();
Run Code Online (Sandbox Code Playgroud)

Ben*_*aum 6

是!!

承诺中的错误传播是其最强大的诉讼之一.它的行为与同步代码完全相同.

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

非常相似:

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

就像在顺序代码中一样,如果你想对错误做一些逻辑而不是将其标记为已处理 - 你重新抛出它:

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
}
Run Code Online (Sandbox Code Playgroud)

哪个成了:

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
});
Run Code Online (Sandbox Code Playgroud)

请注意,在蓝鸟您可以键入和有条件的渔获量,因此,如果你正在做的是一个if类型或承诺的内容,以决定是否要处理它-你可以保存.

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

您还可以使用.error来处理OperationalError源自promisified API的s.通常OperationalError表示您可以从中恢复的错误(与程序员错误相比).例如:

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

这样做的好处是不会TypeError在代码中出现静音或语法错误,这在JavaScript中可能很烦人.