Handling 404, 500 and Exceptions in Node.js and Express
<p>I have a node.js + Express + express-handlebars app. I want to redirect the users to 404 page when they go to a page that does not exists and redirect them to a 500 when there is an internal server error or an exception(without stopping the server). In my app.js I have written the middle ware at the end to perform these tasks.</p>

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

<p>However only the code for 404 works. So if I try to go to an url </p>

<pre><code>localhost:8000/fakepage
</code></pre>

<p>it successfully redirects me to my 404 page. The 505 does not work. And for the exception handling, the server does keep running but, it does not redirect me to the 500 error page after the console.log</p>

<p>I am confused by so many solutions online where people seem to implement different techniques for this. </p>

<p>Here are some of the resources I looked at</p>

<p><a href="http://www.hacksparrow.com/express-js-custom-error-pages-404-and-500.html" rel="noreferrer">http://www.hacksparrow.com/express-js-custom-error-pages-404-and-500.html</a></p>

<p><a href="https://stackoverflow.com/questions/34696848/correct-way-to-handle-404-and-500-errors-in-express">Correct way to handle 404 and 500 errors in express</a></p>

<p><a href="https://stackoverflow.com/questions/6528876/how-to-redirect-404-errors-to-a-page-in-expressjs">How to redirect 404 errors to a page in ExpressJS?</a></p>

<p><a href="https://github.com/expressjs/express/blob/master/examples/error-pages/index.js" rel="noreferrer">https://github.com/expressjs/express/blob/master/examples/error-pages/index.js</a></p>