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 🙁
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:
2- I would recomment to use try{} catch(e) {} on your code, such as:
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
processis going to be replaced in the future with domain5- I’d rather use a framework like express, than doing this stuff.
6- Recommended lecture: StackOverflow – NodeJS best practice for exception handling