【发布时间】:2016-07-06 21:40:23
【问题描述】:
我有一个 node.js + Express + express-handlebars 应用程序。我想在用户转到不存在的页面时将他们重定向到 404 页面,并在出现内部服务器错误或异常时将他们重定向到 500(不停止服务器)。在我的 app.js 中,我在最后编写了中间件来执行这些任务。
app.get('*', function(req, res, next) {
var err = new Error();
err.status = 404;
next();
});
//Handle 404
app.use(function(err, req, res, next){
res.sendStatus(404);
res.render('404');
return;
});
//Handle 500
app.use(function(err, req, res, next){
res.sendStatus(500);
res.render('500');
});
//send the user to 500 page without shutting down the server
process.on('uncaughtException', function (err) {
console.log('-------------------------- Caught exception: ' + err);
app.use(function(err, req, res, next){
res.render('500');
});
});
但是,只有 404 的代码有效。所以如果我尝试去一个 url
localhost:8000/fakepage
它成功地将我重定向到我的 404 页面。 505 不工作。对于异常处理,服务器确实会继续运行,但是它不会在 console.log 之后将我重定向到 500 错误页面
我对网上这么多解决方案感到困惑,人们似乎为此实施了不同的技术。
这是我看过的一些资源
http://www.hacksparrow.com/express-js-custom-error-pages-404-and-500.html
Correct way to handle 404 and 500 errors in express
How to redirect 404 errors to a page in ExpressJS?
https://github.com/expressjs/express/blob/master/examples/error-pages/index.js
【问题讨论】:
标签: javascript node.js express