node.js - Nodejs exception escapes the try/catch block -
var http = require('http'); console.log("subscriberservice.prototype.subscribe("+json.stringify(subscriber)+")"); var options = { host: 'my host goes here', path: 'path goes here', port: '3030', method: 'put', headers: {'content-type': "application/json", 'connection': "close"} }; /* * defines callback executed once http request executed , response received */ var internalcallback = function(response) { console.log('status: ' + response.statuscode); console.log('headers: ' + json.stringify(response.headers)); response.setencoding('utf8'); var str = ''; response.on('data', function (chunk) { str += chunk; }); response.on('end', function () { if(response.statuscode == 201 || response.statuscode == 200) { console.log("success, created new subscriber: " + str); console.log("executing subscriber service success callback"); callback(str); } else { console.log("error, ["+response.statuscode+"] failed create subscriber: " + new error(str)); console.log("executing subscriber service error callback"); errorcallback(new error(str), response.statuscode); } }); response.on('error', function(e) { console.log("error, failed create subscriber: " + e); console.log("executing subscriber service error callback"); errorcallback(e, 500); }); }; try { console.log("executing subscriber put request: dto = " + json.stringify(subscriber)); var req = http.request(options, internalcallback); /* * actual send call executes actual http request subscriber service */ req.write(json.stringify(subscriber)); req.end(); } catch(error) { console.error("failed send request subscriber service: " + error.message); errorcallback("failed send request subscriber service: " + error.message, 500); }
thats code. however, if resource trying connect isnt available or there sort of connection issue exception escapes try/catch , gets caught unhandled exception handler.
i totally confused why. looked through documentation http module , can't figure out. how handle connection errors gracefully.
this error (if resource isn't available , refuses connection)
#sending subscribe request subscriber service: [{"firstname":"","lastname":"","email":"f","ip":"127.0.0.1"}] subscriberservice.prototype.subscribe({"firstname":"","lastname":"","email":"f","ip":"127.0.0.1"}) executing subscriber put request: dto = {"firstname":"","lastname":"","email":"f","ip":"127.0.0.1"} events.js:72 throw er; // unhandled 'error' event ^ error: connect econnrefused @ errnoexception (net.js:904:11) @ object.afterconnect [as oncomplete] (net.js:895:19)
just in example in documentation, should handle errors this:
req.on('error', function(e) { console.log('problem request: ' + e.message); });
errors or exceptions in asynchronous operations not caught try/catch @ higher level. so, have handled separately this.
Comments
Post a Comment