正确处理快递中的404和500错误的方法 [英] Correct way to handle 404 and 500 errors in express

查看:306
本文介绍了正确处理快递中的404和500错误的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正确处理和正确处理404和500错误的正确方法是什么.我读了一些帖子,解释了处理404错误的不同方法.一种是在末尾使用处理程序进行*路由

What is the right way to handle 404 and 500 errors in express and handle them properly.I was reading some posts that explain different ways of handling 404 errors. One was using handler for * route at the end

app.get('*',function(req,res){
                   res.render('404');
          }
       );

我遇到的另一种情况是使用中间件,如下所示

Another one I come across was using middlewares, as below

var express=require('express');
var app=express();

var routes=require('./routes/route.js');

app.set('view engine','ejs');

app.use(express.static(__dirname + '/public'));

app.get('/',routes.home);
app.get('/login',routes.login);


//Handling 404
app.use(function(req, res) {
     res.status(404).render('404');
});


// Handling 500
app.use(function(error, req, res, next) {
     res.status(500).render('500');
});

var port = process.env.PORT || 3000;

var server=app.listen(port,function(req,res){
    console.log("Catch the action at http://localhost:"+port);
});

我正在使用中间件方法,但是仅当我将这些中间件放在所有路由处理程序的最后时,它才起作用.如果我将两个中间件都放在'/'和'/login'的路由处理程序之前,那么它将不起作用.

I am using middleware approach, but it works only when I put those middlewares at the end, which is after all the route handlers. If I put both the middlewares before the route handler for '/' and '/login', It does not works.

这是处理404和500错误的正确方法吗?

Is this the right way to handle 404 and 500 errors?

推荐答案

我发现使用express-generator所使用的方法是理想的.在所有路线的末尾,您包括:

I've found that using the method that express-generator uses to be ideal. At the end of all of your routes you include:

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: {}
  });
});

然后一个示例路由(可能会出错)看起来像这样:

And then an example route (than could have errors) could look like this:

router.get('/', function(req, res, next) {

  err = { message: 'Example error message', error: 'Some error'}

  if(err) next(err);

  if(!err){
    res.render('index', { title: 'Express' });
  }

});

就像@weiyin所说的那样,至少记录您的错误可能是个好主意,以帮助您及时发现问题出在什么地方.

As @weiyin mentioned, it's probably a good idea to at-least log your errors to help keep an eye on when things do go wrong.

这篇关于正确处理快递中的404和500错误的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆