【问题标题】:NodeJs Error handling promise error with in try catch block [duplicate]在try catch块中使用NodeJs错误处理承诺错误[重复]
【发布时间】:2016-09-30 10:34:34
【问题描述】:

我应该如何处理在 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) 有没有更好的方法来处理常见错误?

【问题讨论】:

    标签: javascript node.js error-handling promise


    【解决方案1】:

    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!
    });
    

    这是推荐的方式。

    【讨论】:

    • 更酷的是你可以在你的捕获中恢复(例如重新尝试使用.catch 服务的 AJAX 请求),这样之后的链就不需要中止了。
    猜你喜欢
    • 2020-08-17
    • 2015-10-03
    • 2018-08-01
    • 1970-01-01
    • 2020-08-24
    • 1970-01-01
    • 2014-11-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多