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

标签 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)

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

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

最佳答案

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

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

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

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

<小时/>

已编辑

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

希望对你有帮助

关于node.js - 如何在 Express 中出现未捕获错误后呈现 500 响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25539479/

相关文章:

javascript - 将 CSV 解析为哈希数组

javascript - Baconjs 永无止境的流

javascript - MongoDB update() 函数如何同时具有参数和回调函数?

node.js - 为什么我们不在 NodeJS 应用程序中使用 "express.use"?

javascript - NodeJS 与 Express : Header undefined

javascript - ECONNREFUSED : Connection refused. 为什么?所有其他测试均通过

node.js - 将 Mocha Chai 与 Stormpath 结合使用

node.js - MongoDB 外键查询

node.js - Express js - 套接字 io 连接

javascript - MEAN.JS——请求对象、Express Controller 和 Mongoose 模式