cod*_*ess 2 javascript node.js express
我有一个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');
});
});
Run Code Online (Sandbox Code Playgroud)
但是,只有404的代码有效。因此,如果我尝试转到网址
localhost:8000/fakepage
Run Code Online (Sandbox Code Playgroud)
它成功将我重定向到我的404页面。505不起作用。对于异常处理,服务器确实保持运行,但是在console.log之后,它不会将我重定向到500错误页面。
如此众多的在线解决方案让我感到困惑,因为人们似乎为此采用了不同的技术。
这是我看过的一些资源
http://www.hacksparrow.com/express-js-custom-error-pages-404-and-500.html
https://github.com/expressjs/express/blob/master/examples/error-pages/index.js
uncaughtexception上的进程是针对应用程序进程的-不是针对每个请求的错误处理程序。请注意,它在回调中需要输入一个错误,并且不会传递res。这是一个全局应用程序异常处理程序。最好在全局代码抛出的情况下使用它。
一种选择是,您可以拥有所有正常的路由(在示例中看不到),然后具有404的非错误处理程序的final *最终路由。这始终是最后一条路由,这意味着它已遍及所有其他未找到匹配的路由。 ..因此找不到。这不是一个例外处理情况-您最终知道他们所请求的路径不匹配,因为它已经掉线了。
然后错误路线可以返回500
http://expressjs.com/en/guide/error-handling.html
问题是您有两条错误路线,因此它总是会遇到第一个错误代码,其中硬代码返回404。
express 4工具创建此模式:
var users = require('./routes/users');
// here's the normal routes. Matches in order
app.use('/', routes);
app.use('/users', users);
// catch 404 and forward to error handler
// note this is after all good routes and is not an error handler
// to get a 404, it has to fall through to this route - no error involved
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers - these take err object.
// these are per request error handlers. They have two so in dev
// you get a full stack trace. In prod, first is never setup
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
8667 次 |
最近记录: |