【问题标题】:express error middleware not handling errors thrown from promise.done()表达错误中间件不处理从 promise.done() 抛出的错误
【发布时间】:2012-12-08 00:04:27
【问题描述】:

如果我抛出一个错误,express 会使用 connect errorHandler 中间件很好地呈现它。

exports.list = function(req, res){
  throw new Error('asdf');
  res.send("doesn't get here because Error is thrown synchronously");
};

当我在承诺中抛出错误时,它将被忽略(这对我来说很有意义)。

exports.list = function(req, res){
  Q = require('q');
  Q.fcall(function(){
    throw new Error('asdf');
  });
  res.send("we get here because our exception was thrown async");
};

但是,如果我在 Promise 中抛出错误并调用“完成”节点崩溃,因为中间件没有捕获到异常。

exports.list = function(req, res){
  Q = require('q');
  Q.fcall(function(){
    throw new Error('asdf');
  }).done();
  res.send("This prints. done() must not be throwing.");
};

运行上述命令后,节点崩溃并显示以下输出:

node.js:201
        throw e; // process.nextTick error, or 'error' event on first tick
              ^
Error: asdf
    at /path/to/demo/routes/user.js:9:11

所以我的结论是 done() 不会抛出异常,而是会导致在其他地方抛出异常。是对的吗?有没有办法完成我正在尝试的事情 - 承诺中的错误将由中间件处理?

仅供参考:此 hack 将在顶层捕获异常,但它超出了中间件的范围,因此不适合我的需求(很好地呈现错误)。

//in app.js #configure
process.on('uncaughtException', function(error) {
  console.log('uncaught expection: ' + error);
})

【问题讨论】:

    标签: node.js error-handling express connect


    【解决方案1】:

    也许您会发现connect-domain 中间件对处理异步错误很有用。该中间件允许您像处理常规错误一样处理异步错误。

    var
        connect = require('connect'),
        connectDomain = require('connect-domain');
    
    var app = connect()
        .use(connectDomain())
        .use(function(req, res){
            process.nextTick(function() {
                // This async error will be handled by connect-domain middleware
                throw new Error('Async error');
                res.end('Hello world!');
            });
        })
        .use(function(err, req, res, next) {
            res.end(err.message);
        });
    
    app.listen(3131);
    

    【讨论】:

    • 我认为对我来说困难的部分只是理解 nodejs 的事件循环与我认为理所当然的不兼容。域模块似乎已被引入以某种方式解决这个问题。谢谢! nodejs.org/api/domain.html
    猜你喜欢
    • 2018-01-12
    • 2019-10-20
    • 2017-03-21
    • 1970-01-01
    • 2022-07-25
    • 2015-08-29
    • 2019-01-08
    • 2019-05-04
    • 2018-10-03
    相关资源
    最近更新 更多