javascript - NodeJs 错误处理 try catch block 中的 promise 错误

标签 javascript node.js error-handling promise

我应该如何处理 catch block 中从 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 block 中的错误?

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

最佳答案

Promise 异步工作,使它们在此处的 catch block 的范围之外执行。这就是为什么他们有自己的 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!
});

这是推荐的方式。

关于javascript - NodeJs 错误处理 try catch block 中的 promise 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37562209/

相关文章:

javascript - 如何在 JavaScript 中注册 window.external.notify 事件处理程序

javascript - 我的 Javascript 代码有问题

javascript - 在 Node/Javascript 中链接 HTTP 请求时出现问题

php - 是否可以隐藏特定的PHP通知错误?

javascript - 父 css 文件处理上的 TinyMCE 和多个 CSS 选择器

javascript - 将具有多个小数位的长负数格式化为小数点后 3 位时,它显示为 0.00 而不是 -0.00

php - 关于带有 Web 套接字的 PHP 与与 Node.js 集成或 Node.JS 中的整个站点的思考

javascript - Node.js 单元测试 : Test behaviour when fs module throws error?

jquery - 调试Jquery ajax函数

python - 缺少一个参数时如何引发自己的错误?