javascript - 在 Node.js 和 Express 中处理 404、500 和异常

标签 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');
    });
});

但是只有 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

最佳答案

uncaughtexception 上的进程是针对应用程序进程的——而不是每个请求的错误处理程序。请注意,它在回调中出现错误,并且未传递 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: {}
    });
});

关于javascript - 在 Node.js 和 Express 中处理 404、500 和异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36113101/

相关文章:

javascript - 如何改进我的 'ignore-list' Greasemonkey 脚本?

javascript - 防止 Jasmine 中的 onComplete 退出

node.js - Ubuntu 16.04 无法运行 npm run/install/rebuild

在我的 Express 应用程序中找不到 javascript 文件

javascript - 如何使用js和php创建类似于Google analytic的跟踪脚本?

javascript - 如何解决这个 "unreachable code after return statement"警告?

javascript - Firebase 存储 : string does not match format base64: invalid character found. 仅当调试关闭时

node.js - 如何处理对请求进行速率限制的api?

javascript - 如何解码nodejs中的URL?

javascript - Nodejs服务器没有收到来自POST请求的任何参数