Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to stop node js server from crashing

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 :(

like image 963
Goje87 Avatar asked Jan 13 '13 17:01

Goje87


2 Answers

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

like image 140
Tom Roggero Avatar answered Oct 02 '22 04:10

Tom Roggero


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.

like image 20
Airy Avatar answered Oct 02 '22 05:10

Airy