4

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

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.

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

Mahtab Alam
  • 1,810
  • 3
  • 23
  • 40

2 Answers2

3

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

});

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.

Ash
  • 6,483
  • 7
  • 29
  • 37
1

Express matches routes in the order you add them, so that's why the catch-all 404 route only works if you put it at the end. Handling 500 errors that way is fine, but at the very least you should log them too.

weiyin
  • 6,819
  • 4
  • 47
  • 58
  • Logging yes 100%...but best bet is to email dev when any 500 occurs. I do this in Django seamlessly and ran across this post. If your development team gets notified of errors immediately, problems get fixed faster – ViaTech Jan 21 '23 at 03:14