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:
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
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.