我可以重复使用express.js错误视图吗?
问题描述:
当express无法找到一个视图时,它会出错并且(在调试模式下)呈现一个漂亮的页面。有没有一种方便的方式来重新使用该视图来处理我自己的错误消息?我可以重复使用express.js错误视图吗?
答
我不知道如何重用视图,但可以使用error.stack来渲染堆栈跟踪。
我有这样的事情:
app.all('*', function(req, res){
var code = 404;
res.local('error', { type: 'http', code: code });
res.local('code', code);
res.render('errors/index', { status: code });
});
app.error(function(err, req, res, next){
var code;
if(err.type === 'http'){
code = err.error;
}
else {
code = 500;
};
if(err){
res.local('stack', err.stack || JSON.stringify(err, null, 2));
};
res.local('code', code);
res.render('errors/index', { status: code });
});
如果我需要手动设置像404我做我的看法如下:
next({type:'http', error: 404});
这其中有一个类型检查在我观点。
现在我相信app.error已被折旧。 – UpTheCreek 2012-10-31 16:14:14
是的。您现在需要使用带4个参数的中间件功能。函数(err,req,res,next){//用err做东西} – Pickels 2012-10-31 19:55:39