How to Handle 500 Errors at Express.js

2014/06/142 min read
bookmark this
Responsive image

Table of Contents

  1. Global Handler
  2. Handling Errors in Callbacks

Introduction

If you don't handle errors correctly, your site will go down. This post shows a few tips on how to do error handling in Express.js.

Global Handler

Write the following so that every time a 500 error happens in Express.js, it will go to the site_500.jade view. This is going to work in most cases. However, it doesn't work if you have an error inside a callback function.

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

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

Handling Errors in Callbacks

Code like the following will make your site go down. Even though you add the above logic to handle 500 errors, it will not work.

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

Yes, you can use try/catch.

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

Conclusion

Handling 500 errors in Express.js requires both a global error handler middleware and proper try/catch blocks inside callback functions. The global handler catches most errors, but errors inside callbacks need to be wrapped in try/catch to prevent your application from crashing.