使用process.on(' uncaughtException显示500错误页面

时间:2012-04-19 03:36:30

标签: node.js error-handling express

我正在开发一个快速应用程序。

我目前在server.js

中有以下内容
process.on('uncaughtException', function (err) {
    console.log( "UNCAUGHT EXCEPTION " );
    console.log( "[Inside 'uncaughtException' event] " + err.stack || err.message );
});

每当出现错误时停止服务器崩溃,但是,它只是坐在那里......

是否可以代替console.log发送包含错误详细信息的500错误页面?

2 个答案:

答案 0 :(得分:8)

我认为你不能在uncaughtException内做出回应,因为即使没有请求发生也可能发生这种情况。

Express本身为路由中的handle errors提供了一种方式,如下所示:

app.error(function(err, req, res, next){
    //check error information and respond accordingly
});

答案 1 :(得分:4)

根据ExpressJS Error Handling,在您的其他app.use(function(err, req, res, next){ // your logic });语句下方添加app.use

示例:

app.use(function(err, req, res, next){
  console.log(err.stack);
  // additional logic, like emailing OPS staff w/ stack trace
});