使用 bluebird Promise 进行异步异常处理

2024-01-13

处理这种情况的最佳方法是什么。我处于受控环境中,我不想崩溃。

var Promise = require('bluebird');

function getPromise(){
    return new Promise(function(done, reject){
        setTimeout(function(){
                throw new Error("AJAJAJA");
        }, 500);
    });
}

var p = getPromise();
    p.then(function(){
        console.log("Yay");
    }).error(function(e){
        console.log("Rejected",e);
    }).catch(Error, function(e){
        console.log("Error",e);
    }).catch(function(e){
        console.log("Unknown", e);
    });

当从 setTimeout 中抛出时,我们总是会得到:

$ node bluebird.js

c:\blp\rplus\bbcode\scratchboard\bluebird.js:6
                throw new Error("AJAJAJA");
                      ^
Error: AJAJAJA
    at null._onTimeout (c:\blp\rplus\bbcode\scratchboard\bluebird.js:6:23)
    at Timer.listOnTimeout [as ontimeout] (timers.js:110:15)

如果抛出发生在 setTimeout 之前,则 bluebirds catch 将拾取它:

var Promise = require('bluebird');

function getPromise(){

    return new Promise(function(done, reject){
        throw new Error("Oh no!");
        setTimeout(function(){
            console.log("hihihihi")
        }, 500);
    });
}

var p = getPromise();
    p.then(function(){
        console.log("Yay");
    }).error(function(e){
        console.log("Rejected",e);
    }).catch(Error, function(e){
        console.log("Error",e);
    }).catch(function(e){
        console.log("Unknown", e);
    });

结果是:

$ node bluebird.js
Error [Error: Oh no!]

这很棒 - 但如何在节点或浏览器中处理这种性质的恶意异步回调。


承诺不是domains http://www.nodejs.org/api/domain.html,它们不会捕获异步回调的异常。你就是不能那样做。

然而,Promise 确实会捕获从内部抛出的异常。then / catch / Promise构造函数回调。所以使用

function getPromise(){
    return new Promise(function(done, reject){
        setTimeout(done, 500);
    }).then(function() {
        console.log("hihihihi");
        throw new Error("Oh no!");
    });
}

(要不就Promise.delay https://github.com/petkaantonov/bluebird/blob/master/API.md#promisedelaydynamic-value-int-ms---promise)以获得所需的行为。永远不要抛出自定义(非承诺)异步回调,始终拒绝周围的承诺。使用try-catch如果确实需要的话。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 bluebird Promise 进行异步异常处理 的相关文章

随机推荐