我在 Express 中使用自定义错误页面,如此处所述。
但是当我这样做时,我只看到错误消息。我想获取与默认 Express 错误处理程序(堆栈跟踪等)中显示的相同信息,以便我可以:
- 将其记录到控制台(如果我可以为此保留默认设置,我会很高兴)。
- 在错误页面上显示它,但仅适用于 localhost。
我该怎么做呢?
这是@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;
});
只需使用提供给中间件的错误
// 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);
}
});