expression错误中间件不处理从promise.done()抛出的错误

如果我抛出一个错误,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中抛出一个Error并且调用“done”节点崩溃,因为这个exception不被中间件捕获。

 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()不是抛出exception,而是导致抛出exception。 是对的吗? 有没有一种方法可以完成我正在尝试的 – 在承诺中的错误将由中间件来处理?

仅供参考:这种黑客将捕捉到顶级的exception,但它不在中间件领域,所以不适合我的需要(很好地呈现错误)。

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

也许你会发现连接域中间件可用于处理asynchronous错误。 这个中间件可以让你像处理常规错误一样处理asynchronous错误。

 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);