Alvaro Alvaro - 8 days ago 6
Javascript Question

Prevent Express.js from crashing

I'm quite new to Express.js and one of the things that surprised me more at first, compare to other servers such as Apache or IIS, is that Express.js server crashes every time it encounters an uncatched exception or some error turning down the site and making it accessible for users. A terrible thing!

For example, my application is crashing with a Javascript error because a variable is not defined due to a name change in the database table.


TypeError: Cannot call method 'replace' of undefined


This is not such a good example, because I should solve it before moving the site to production, but sometimes similar errors can take part which shouldn't be causing a server crash.

I would expect to see an error page or just an error in that specific page, but turning down the whole server for these kind of things sounds terrifying.

Express error handlers doesn't seem to be enough for this purposes.

I've been reading about how to solve this kind of things in Node.js by using domains, but I found nothing specifically for Express.js.

Another option I found, which doesn't seem to be recommended in all cases, is using tools to keep running a process forever, so after a crash, it would restart itself. Tools like Forever, Upstart or Monit.

How do you guys deal with this kind of problems in Express.js?

Answer

The main difference between Apache and nodejs in general is that Apache forks a process per request while nodejs is single threaded, hence if an error occurs in Apache then the process handling that request will crash while the others will continue to work, in nodejs instead the only thread goes down.

In my projects I use monit to check memory/cpu (if nodejs takes to much resources of my vps then monit will restart nodejs) and daemontools to be sure nodejs is always up and running.