node.js - 表达错误中间件不处理从promise.done()抛出的错误

标签 node.js error-handling express connect

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

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

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

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 中抛出错误并调用“done”, Node 就会崩溃,因为中间件没有捕获异常。

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 崩溃并显示以下输出:

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() 没有抛出异常,而是导致在其他地方抛出异常。是对的吗?有没有办法完成我正在尝试的事情 - promise 中的错误将由中间件处理?

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

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

最佳答案

也许你会发现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);

关于node.js - 表达错误中间件不处理从promise.done()抛出的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13772981/

相关文章:

javascript - Node.js - "Uncaught Error: Cannot find module "redis“”

php - 获取 Laravel Model->save() 错误代码或消息

python - 转换字节->字符串->返回字节,并获取原始值

node.js - Express.js 使用创建额外的路由

javascript - 如何将多个集合数据从mongodb渲染到node js中的页面

node.js - Lambda 始终返回 200

node.js - Sails mongo 重新连接

node.js - 子文件与 Mongoose 人口

makefile - 如何使某些警告失败,而不是其他警告

node.js - 是否可以一起使用 winston 日志记录和调试模块?