处理 Node.js 和 Express 中的 404、500 和异常

Handling 404, 500 and Exceptions in Node.js and Express

本文关键字:异常 Express Node js 处理 中的      更新时间:2023-09-26

我有一个节点.js + Express + express-handlebars app。我想在用户转到不存在的页面时将用户重定向到 404 页面,并在出现内部服务器错误或异常(不停止服务器)时将他们重定向到 500。在我的应用程序中.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 的代码有效。因此,如果我尝试转到网址

localhost:8000/fakepage

它成功地将我重定向到我的 404 页面。505 不起作用。对于异常处理,服务器确实继续运行,但它不会在控制台后将我重定向到 500 错误页面.log

我对网上这么多解决方案感到困惑,人们似乎为此实施了不同的技术。

以下是我查看的一些资源

http://www.hacksparrow.com/express-js-custom-error-pages-404-and-500.html

处理快递中404和500错误的正确方法

如何将 404 错误重定向到 ExpressJS 中的页面?

https://github.com/expressjs/express/blob/master/examples/error-pages/index.js

uncaughtexception 上的进程适用于应用程序进程 - 而不是每个请求的错误处理程序。 请注意,它在回调中犯了一个错误,并且 res 没有传递。 它是一个全局应用程序异常处理程序。 最好在全局代码抛出的情况下拥有它。

一种选择是您可以拥有所有正常路由(在您的示例中看不到),然后是 404 的非错误处理程序 final * 路由。 这始终是最后一条路线,这意味着它已经通过所有其他路线没有找到匹配......因此找不到。 这不是一个异常处理案例 - 您最终知道他们请求的路径不匹配,因为它已经失败了。

如何将 404 错误重定向到 ExpressJS 中的页面?

那么错误路线可以返回 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: {}
    });
});