3

我在 Express 中使用自定义错误页面,如此所述。

但是当我这样做时,我只看到错误消息。我想获取与默认 Express 错误处理程序(堆栈跟踪等)中显示的相同信息,以便我可以:

  1. 将其记录到控制台(如果我可以为此保留默认设置,我会很高兴)。
  2. 在错误页面上显示它,但仅适用于 localhost。

我该怎么做呢?

4

2 回答 2

7

这是@generalhenry 回答的修改版本。您可以访问堆栈跟踪,err.stack以便您可以将它传递到您的“500”视图并对其进行一些花哨的 css 样式。

app.use(function(err, req, res, next) {
   if (err instanceof NotFound) {
       res.render('errors/404');
   } else {
       res.render('errors/500', {error: err, stack: err.stack});
   }
});

function NotFound() {
   this.name = "NotFound";
   Error.call(this, msg);
   Error.captureStackTrace(this, arguments.callee);
}

// below all route handlers
// If all fails, hit em with the 404
app.all('*', function(req, res){
   throw new NotFound;
});
于 2013-04-18T09:00:19.160 回答
0

只需使用提供给中间件的错误

  // Handle 500
  app.use(function(error, req, res, next) {
     console.error(error);
     if (ISLOCALHOST()) {
       res.json(error, 500);
     } else {
       res.send('500: Internal Server Error', 500);
     }
  });
于 2013-03-27T08:23:18.020 回答