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?