从进程未捕获异常访问 res/req



app.js

_app.configure(function()
{
    /**
     * app setup
     */
    _app.set('port', process.env.PORT || 3000);
    _app.use(express.methodOverride());
    _app.use(function(req, res, next){
        console.log('%s %s', req.method, req.url);
        next();
    });
    _app.use(_app.router);
    _app.use(express.static(__dirname+'/public'));
});
process.on('uncaughtException', function (err, req, res) {
    console.log( res );
    _winston.error(err.message, err.code);
});

当未捕获发生时,我可以在控制台中显示消息,但我也想向浏览器发送 JSON 响应。我该怎么做?如何从未捕获的异常访问 res/req?

谢谢!

据我所知,这是不可能的,因为未捕获的异常可能不仅发生在快速回调中,而且可能发生在代码中的任何位置。您可能需要使用快速错误处理程序:

_app.error(function(err, req, res, next) {
   res.json({ ... });
});

本模块:https://github.com/baryshev/connect-domain 通过使用域(http://nodejs.org/api/domain.html)来解决此问题。这是一个简单的连接中间件,你像这样使用(取自他们的github页面):

var
    connect = require('connect'),
    connectDomain = require('connect-domain');
var app = connect()
    .use(connectDomain())
    .use(function(req, res){
        if (Math.random() > 0.5) {
            throw new Error('Simple error');
        }
        setTimeout(function() {
            if (Math.random() > 0.5) {
                throw new Error('Asynchronous error from timeout');
            } else {
                res.end('Hello from Connect!');
            }
        }, 1000);
    })
    .use(function(err, req, res, next) {
        res.end(err.message);
    });
app.listen(3000);

我一直在使用这个模块上取得了成功,一个提示是观察您将在堆栈中引入连接域的位置:https://github.com/baryshev/connect-domain/issues/12

最新更新