8

I've got a node.js app hosted on Heroku

Whenever my app encounters an error, the whole server crashes, making it unavailable for anyone.

Is there any way to return an error page instead, and keep the server alive?

I read this, Node.JS with forever on Heroku but it didn't answer my question....

Community
  • 1
  • 1
Alex
  • 37,502
  • 51
  • 204
  • 332
  • I *half* figured this out - however, i'm having trouble sending an error page - http://stackoverflow.com/questions/10221309/use-process-onuncaughtexception-to-show-a-500-error-page – Alex Apr 19 '12 at 03:36
  • I found another similar post with good answer. Please check [here][1] [1]: http://stackoverflow.com/questions/5999373/how-do-i-prevent-node-js-from-crashing-try-catch-doesnt-work – Sadaka Jul 25 '14 at 05:51

2 Answers2

8

http://nodejs.org/docs/latest/api/process.html#process_event_uncaughtexception

You can listen for the uncaughtException event and then do your error handling. Ideally, your callbacks should return an err argument and then do the error handling.

liangzan
  • 6,804
  • 4
  • 29
  • 28
4

You can probably use DOMAIN, this will probably stop your server from crashing when an uncaughtException is thrown.

domain = require('domain'),
d = domain.create();

d.on('error', function(err) {
  console.error(err);
});

for more details go http://shapeshed.com/uncaught-exceptions-in-node/

beside using this method must try-catch your block.

Airy
  • 5,484
  • 7
  • 53
  • 78
  • 1
    I know this is an old post, but just to update: **DOMAIN** has been deprecated and should no longer be used. – Azevedo Sep 04 '16 at 16:17
  • @Azevedo Thanks for your update but unfortunately there is no other better replacement provided by Node Docs. You can further read here http://stackoverflow.com/questions/5999373/how-do-i-prevent-node-js-from-crashing-try-catch-doesnt-work – Airy Sep 05 '16 at 15:16