0

我正在使用连接域模块 ( https://github.com/baryshev/connect-domain ) 在我的 Express 应用程序中集中错误处理。

在大多数情况下,它都有效。但是,由于我不明白的原因,当我在 fs.exists 检查中抛出错误时,它不会捕获错误而是使节点崩溃。

app.get( "/anurl/", function( req, res ){
    ...
    fs.exists( filename, function( exists ) {
        if ( !exists ) throw new Error( "bah!" );
        ...
    });
});

编辑:

经过相当多的测试,我了解到上述不是问题的真正原因。

实际问题与使用 Redis 作为会话存储有关:

app.use( connectDomain() );
app.use( express.session({
    secret: "secretz",
    store: new RedisStore({ client: redis })
}));

使用上述内容,connectDomain 不再适用于异步抛出的任何错误。(这包括对文件系统、超时、数据库连接等的调用)

如果我将以上内容更改为以下内容...

app.use( connectDomain() );
app.use( express.session({ secret: "secretz" }));

...然后一切正常。

所以关于 RedisStore 的一些东西正在破坏 Connect-Domain。不幸的是,我需要使用 Redis 来保持我的会话。

任何有关如何解决此问题的进一步建议将不胜感激。

4

2 回答 2

2

我刚刚尝试使用此代码:

var http = require('http');
var express = require('express');
var connectDomain = require('connect-domain');
var fs = require('fs');

var app = express();
app.use(connectDomain());

app.get('/', function (req, res) {
    fs.exists('test', function (err) {
        if (!err) throw new Error('bah!');
        res.writeHead(200, {'Content-Type': 'text/plain'});
        res.end('Hello World\n');
    });
});

app.use(function (err, req, res, next) {
    res.end(err.message);
});

http.createServer(app).listen(1339, '0.0.0.0');

错误被成功捕获。

node.js: 0.10.1

connect-domain: 0.5.0

于 2013-04-01T10:42:39.387 回答
0

看看是否与以下相关:

“扔与扔新”的东西

http://www.javascriptkit.com/javatutors/trycatch2.shtml

于 2013-04-01T02:13:19.673 回答