如何在 Express 中出现未捕获错误后呈现 500 响应?

sam*_*mol 9 node.js express

app.get('/', function(req, res) {
   doSomethingAsync(function(err) {
      throw new Error('some unexpected/uncaught async exception is thrown');
   })
})

Possibly unhandled Error: some unexpected/uncaught async exception is thrown
    at ...stacktrace...:95:9
From previous event:
    at ...stacktrace...:82:6)
    at ...stacktrace...:47:6)
    at ...stacktrace...:94:18)
Run Code Online (Sandbox Code Playgroud)

我已经尝试了一堆域中间件,但它们都只适用于 Express 3。我目前使用的是 Express 4.5,我想知道 Express 是否已更改该域不再工作。

目前,当抛出异常时,响应基本上会挂起,直到超时。

Dec*_*yFx 3

假设您遇到的错误是在路由器或控制器内部,在监听之前将其放在应用程序配置的最末尾

app.use(function(err, req, res) {
    res.status(err.status || 500);
    // if you using view enggine
    res.render('error', {
        message: err.message,
        error: {}
    });
    // or you can use res.send();        
});
Run Code Online (Sandbox Code Playgroud)

您的应用程序将捕获任何未捕获的路由器错误并呈现“错误”页面

顺便说一句,不要忘记在路由器初始化中包含“下一步”


已编辑

app.get('/', function(req, res, next) {
    try {
        signin(req.query.username, req.query.password, function(d){
            if (d.success) {
                req.session.user = d.data; 
            } 
            res.end(JSON.stringify(d));
        });
    } catch(e) {
        next(e);
    }
}
Run Code Online (Sandbox Code Playgroud)

希望有帮助