node.js error when an http.request is issued to a server that is not responding
I am writing a node.js server which acts as an API between a client and a java server that is one step downstream of the node.js API. The API accepts incoming HTML requests from the client, reformats them, and sends them out to the java server, which returns its answer to the node.js API, which returns it back to the client. This all works beautifully, except for when the server is down. i need to catch that event, just like I can catch a 502 or a 302... here is my code:
async.waterfall(
[
function(callback){
var options = { host: 'localhost', port: '8080',
path: '/javaServerWork/' + req.query.foo + '?toDo=' + req.query.bar,
method: 'GET',
headers: { accept: 'application/json' }
};
http.request(options, function(response){
response.on('error', function(exception) { Console.log("error here"); }
if(response.statusCode == '200'){ callback(null, response); }
else if (response.statusCode == '502') { res.send('502'); }
else { res.send('not 200 and not 502'); }
}).end();
},
function(response){
var javaResponse = '';
response.on('error', function(exception){ Console.log("error here");});
response.on('data', function (chunk){ javaResponse += chunk; });
response.on('end', function(){
res.send(javaResponse);
})
}
]
);
when i start up this node server and issue a request to the node.js server which then attempts to reach the java server, node.js crashes and i get the following error in my console:
events.js:69 throw arguments[1]; // Unhandled 'error' event ^ Error: connect ECONNREFUSED at errnoException (net.js:846:11) at Object.afterConnect [as oncomplete] (net.js:837:19)
All I need to do is catch the "no response" when the java server is down, so that i can execute another function or simply return that fact back to the client, of course, without node crashing! This may be very simple, but i have found nothing that works. I have tried process.on('uncaughtException'), I have tried (as in the code) response.on('error').
I am new to node and can't see where the problem is... Any help greatly appreciated!
Did you try
http.request(options, function(response){
response.on('error', function(exception) { Console.log("error here"); }
if(response.statusCode == '200'){ callback(null, response); }
else if (response.statusCode == '502') { res.send('502'); }
else { res.send('not 200 and not 502'); }
}).on('error', function(e) {
console.log("handle error here");
}).end();
Sounds like the error is being thrown on the request object that http.request returns, not on the response object
(http://nodejs.org/api/http.html#http_http_request_options_callback)
链接地址: http://www.djcxy.com/p/46458.html上一篇: 在快递中处理异常