如何正确处理请求承诺错误?

Rav*_*rsT 5 javascript node.js promise

所以我在一个脚本中使用了request-promise,这个脚本循环遍历url和请求的激活列表.然后,我希望在所有请求完成后,接收数据.

我有以下内容:

var rp = require('request-promise');

rp.get({
    uri: 'http://httpstat.us/500',
    transform: function(body, res){
        res.data = JSON.parse(body);
        return res;
    }
}).then(function(res){
    results.push(res.data);
})
.catch(function(err){
    should.throw.error.to.console();
    var respErr  = JSON.parse(err.error);
    var errorResult = {
        origUrl: respErr.origUrl,
        error: respErr
    };
    results.push(errorResult);
});
Run Code Online (Sandbox Code Playgroud)

正如你所看到的.. http://httpstat.us/500抛出一个500,这将导致.catch()块中跑去.我在逼错. should.throw.error.to.console();应该向控制台抛出错误,但是,脚本只是静默退出,没有任何错误代码(Process finished with exit code 0).

我假设http当一个页面没有返回w/2xx代码然后将其传递回catch()回调时,请求承诺正在捕获节点的错误.但任何后续错误最终都会以无声的方式失败.我如何处理这个问题,以便我的其余代码仍能正确抛出错误?

相关的GitHub 问题

Rav*_*rsT 0

显然,promise 中的 .catch() 基本上是 JS try-catch 的包装器。因此,为了在编写一个处理程序后将后续错误记录到控制台,您必须有第二个处理程序将最终的错误抛出到控制台。

有关 GitHub 的更多信息,请访问:https://github.com/request/request-promise/issues/48#issuecomment-107734372