6

I am new to node js. I was trying to create a simple HTTP server. I followed the famous example and created a 'Hello World!' server as follows.

var handleRequest = function(req, res) {
  res.writeHead(200);
  res1.end('Hello, World!\n');
};

require('http').createServer(handleRequest).listen(8080);

console.log('Server started on port 8080');

Running this code would start the server properly as expected. But trying to access http://127.0.0.1:8080 would crash it by throwing an error that res1 is not defined. I would like to have the server still continue running and gracefully report errors whenever it encounters it.

How do I achieve it? I tried try-catch but that isn't helping me :(

Goje87
  • 2,839
  • 7
  • 28
  • 48
  • 2
    See http://stackoverflow.com/a/8114990/435413 (autoreboot javascript) or http://stackoverflow.com/questions/5999373/how-do-i-prevent-node-js-from-crashing-try-catch-doesnt-work (prevent crash) – sod Jan 13 '13 at 18:01
  • 1
    Hi Benjamin, I purposefully typed it as res1 to generate error. My question is about how to handle such errors without crashing the server. – Goje87 Jan 13 '13 at 18:45

3 Answers3

6

There are a bunch of comments here. First of all, for your example server to work, handleRequest needs to be defined BEFORE using it.

1- What you actually want, which is preventing the process to exit, can be handled by handling uncaughtException (documentation) event:

var handleRequest = function(req, res) {
    res.writeHead(200);
    res1.end('Hello, World!\n');
};
var server = require('http').createServer(handleRequest);
process.on('uncaughtException', function(ex) {
    // do something with exception
});
server.listen(8080);
console.log('Server started on port 8080');

2- I would recomment to use try{} catch(e) {} on your code, such as:

var handleRequest = function(req, res) {
    try {
      res.writeHead(200);
      res1.end('Hello, World!\n');
    } catch(e) {
      res.writeHead(200);
      res.end('Boo');
    }
};

3- I guess the example was just an example and not actual code, this is a parsing error that can be prevented. I mention this, since you NEED to NOT have parsing errors on Exception catch handlers.

4- Please note that node process is going to be replaced in the future with domain

5- I'd rather use a framework like express, than doing this stuff.

6- Recommended lecture: StackOverflow - NodeJS best practice for exception handling

Community
  • 1
  • 1
Tom Roggero
  • 5,777
  • 1
  • 32
  • 39
  • 1 is wrong, 2 is wrong for asynchronous code, 4 is wrong since process is going to be complemented with domain, and domain also works now – Benjamin Gruenbaum Jan 13 '13 at 17:46
  • 1
    @BenjaminGruenbaum 1 why? Explain further + it actually works and prevents the app to crash. 2 author never says he needs to handle parse exceptions on async code. 4 domain is in unstable version and node docs says explicitly "use domain INSTEAD OF process" – Tom Roggero Jan 13 '13 at 17:50
  • Thanks Tom... ponint 1 worked for me... And I will follow your suggestions. I will consider using express. – Goje87 Jan 13 '13 at 18:46
1

I am not targeting your question details but your question's title about preventing Node server from crashing. 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
0

Maybe you should define handleRequest before you use it:

require('http').createServer(handleRequest).listen(8080);

function handleRequest(req, res) {
  res.writeHead(200);
  res1.end('Hello, World!\n');
};

Or

var handleRequest = function(req, res) {
  res.writeHead(200);
  res1.end('Hello, World!\n');
};

require('http').createServer(handleRequest).listen(8080);

And you should be sure that res1 also exists.

Andreas Louv
  • 46,145
  • 13
  • 104
  • 123
  • 1
    Nope, javascript automatically moves "var" statements to the top of the scope. – Benjamin Gruenbaum Jan 13 '13 at 17:45
  • 1
    Hi @NULL, Yes... the handleRequest should be above the createServer line. My bad. I copy-pasted it wrongly (updating the question now). Now, coming to res1 error, I know the cause of the error. I was trying to ask about gracefully handling it. – Goje87 Jan 13 '13 at 17:47
  • @BenjaminGruenbaum Yes `handleRequest` is defined but is `undefined` . It's like writing: `var a; b(a) a = function(){...}` – Andreas Louv Jan 13 '13 at 22:51
  • no, @BenjaminGruenbaum is right. function declarations are hoisted (which is different from anon function assignment to a var) – Andrey Sidorov Jan 14 '13 at 00:52
  • yeah, this way undefined is passed to a function. – Andrey Sidorov Jan 14 '13 at 04:15