【问题标题】:Restify & Bluebird - how to pass an error from a catch block to restify error handler?Restify & Bluebird - 如何将错误从 catch 块传递到 restify 错误处理程序?
【发布时间】:2015-11-17 11:36:27
【问题描述】:

我正在使用 node js 服务器,并使用 bluebird 来实现 promise。我了解如何使用承诺,但我的问题是如何处理从承诺返回的错误。我尝试了简单的解决方案 - 只是再次抛出错误 - 但蓝鸟抓住了它,客户端永远不会收到响应。波纹管是一个演示代码,以说明我的问题:

var restify = require('restify');
var Promise = require('bluebird');

var server = restify.createServer({
  name: 'myapp',
  version: '1.0.0'
});

server.get('/', function (req, res, next) {
    new Promise(function(resolve, reject){
        reject(new Error());
    }).then(function(res){
        res.send('hello');
    }).catch(function(e){
        throw e;
    });
});

server.on('uncaughtException', function (req, res, route, error) {
    console.log('error');
});

server.listen(7070, function () {
  console.log('%s listening at %s', server.name, server.url);
});

我正在寻找一种方法来以某种方式将错误传递给 restify,因此它将引发 uncaughtException 事件,我可以像处理任何其他未捕获的异常一样处理它。经过一番搜索后,我发现我可以简单地执行next(new InternalServerError()) 之类的操作,restify 会针对此特定错误引发一个事件,但这对我来说看起来有点奇怪,所以我正在寻找更好的方法。

【问题讨论】:

    标签: javascript promise bluebird restify


    【解决方案1】:

    这是一个 PoC,它将重新抛出任何“可能未处理的拒绝”。这些将随后触发 Restify 的 uncaughtException 事件:

    var Promise = require('bluebird');
    var restify = require('restify');
    var server  = restify.createServer();
    
    server.listen(3000);
    
    Promise.onPossiblyUnhandledRejection(function(err) {
      throw err;
    });
    
    server.get('/', function (req, res, next) {
      Promise.reject(new Error('xxx')); // no `.catch()` needed
    });
    
    server.on('uncaughtException', function (req, res, route, err) {
      console.log('uncaught error', err);
      return res.send(500, 'foo');
    });
    

    【讨论】:

    • 谢谢!这看起来像我想要的。
    • 好的,这仅在错误中没有消息时才有效 - 因为 restify 呈现响应(使用错误消息)然后调用 after 事件处理程序。这使得所有这些解决方案对我来说有点无关紧要......
    • 我试图在我的机器上运行它,似乎restify域没有捕获到异常。我添加了process.on('uncaughtException',,它捕获了异常,但这并没有多大帮助,因为我无法向客户返回一些东西。如果我能找到使用 restify 域的方法,我会尝试稍后查看。
    • @omer fwiw,我正在使用 restify@4.0.0bluebird@2.9.34node@0.12.7
    • 所以这可能是我的restify版本,我刚刚注意到我使用的是过时的restify(3.0.3)。我会检查后者,但如果它适合你,这可能是解决方案。
    猜你喜欢
    • 1970-01-01
    • 2015-04-30
    • 1970-01-01
    • 2013-08-19
    • 1970-01-01
    • 2014-03-17
    • 2017-05-04
    • 2015-10-28
    • 1970-01-01
    相关资源
    最近更新 更多