NodeJs错误处理承诺错误与try catch块

时间:2016-06-01 07:32:40

标签: javascript node.js error-handling promise

如何处理catch块中的promise抛出的错误?

例如,

try {

    // some other functions/code that can also throw error

    var promise = // a service that returns new Promise() object 

    promise.then(function(data) {
        //some business logic
    }, function(err) {
        throw new Error(err); // never gets caught in catch block
    });
} catch(error) {
    // do something with error
    console.log(error);
}

1)是否可以处理从promise中抛出的try catch块中的错误?

2)是否有更好的方法来处理常见错误?

1 个答案:

答案 0 :(得分:3)

Promise异步工作,使它们在你所拥有的catch块的范围之外执行。这就是他们拥有自己版本catch -

的原因
promise
.then(function(data) {
    //some business logic
    return anotherPromise;
 })
.then(function(data) {
    //some other business logic
 })
 // this keeps chaining as long as needed
.catch(function(err) {
    // You will get any thrown errors by any of the
    // chained 'then's here.
    // Deal with them here!
});

这是推荐的方法。