How to Handler 500 Error at Express.js

2014/6/141 min read
bookmark this
Responsive image

How to hanlder 500 error on Express.js

If you don't handler error correctly, you site will down. This blog show little tips that how to do error handler on express.js.

global hander

writing following, so everytime 500 happen at express.js, will go to site_500.jade view. This is going to work at most of the case. However, don't work if you have error on callback function.


 app.use(function (err, req, res, next) {
            if (err.status !== 500) {
                return res.render('site_500.jade');
            }           

            res.send('error');
        });

Code like following will make your site down. Eventhough you add above logic to handler 500 error, it will not work.


request(options, function (error, response, body) {
        // this will make your site down
        var data = JSON.parse('sfas');
    });

Yes, you can do try/catch.


request(options, function (error, response, body) {
        // this will work
try
{
        var data = JSON.parse('sfas');
}
catch()
{}
    });