【问题标题】:Handling 404, 500 and Exceptions in Node.js and Express在 Node.js 和 Express 中处理 404、500 和异常
【发布时间】: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


    【解决方案1】:

    未捕获异常的进程用于应用程序进程 - 不是每个请求的错误处理程序。请注意,它的回调中有一个错误,并且 res 没有传递。它是一个全局应用程序异常处理程序。如果您的全局代码抛出异常,最好有它。

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

    How to redirect 404 errors to a page in ExpressJS?

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

    【讨论】:

    • var profile = require('./routes/profile); app.use('/profie', profile);这就是我定义所有路线的方式。
    • 没关系 - 这些路由应该在 404 路由和错误路由之前设置 - 基本上是上面设置 / 和 /users 路由的位置。路线排序至关重要
    • 这正是上面的示例所做的。它通过要求用户加载用户功能,并通过传递用户设置 /users 路由。 然后设置完所有路由后添加404通配符路由,最后报错500路由
    • 感谢您的样品。我让 404 在旧代码中工作,我仍然无法处理异常。例如,假设 URL 是 /students/we232(其中 we232 是学生 ID)。如果我将其更改为乱码或不存在的内容,我希望将用户定向到 500 而不是关闭服务器。我如何做到这一点?
    • 在您概述的情况下,获取学生路线将查找 we232,最终发现它不存在并返回 404(在这种情况下应该做什么)。在这种情况下,每个请求未处理的处理程序(err、req、res、next)不会被调用,因为它已被“处理​​”。 500 用于未处理的服务器错误。当然,服务器不会关闭,因为 (1) 它是在该路由函数中处理的,并且 (2) 即使它以某种方式没有得到处理,它也会返回 500。 uncaughtexception 上的应用程序级别不是每个请求处理程序 - 它是用于处理应用中的全局异常
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-13
    • 1970-01-01
    • 2016-07-29
    • 1970-01-01
    • 2012-10-25
    相关资源
    最近更新 更多