2015-05-12 56 views
0
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 a callback which will be executed once the HTTP request is executed and the response is 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 to 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 to 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); 

    /* 
    * This is the actual send call which executes the actual HTTP request to the subscriber service 
    */ 
    req.write(JSON.stringify(subscriber)); 
    req.end(); 
} 
catch(error) { 

    console.error("Failed to send request to subscriber service: " + error.message); 
    errorCallback("Failed to send request to subscriber service: " + error.message, 500); 
} 

這就是我的代碼。但是,如果我嘗試連接的資源不可用,或者存在任何連接問題,該異常將轉義我的try/catch並被未處理的異常處理程序捕獲。Nodejs異常轉義try/catch塊

我完全不知道爲什麼。我瀏覽了http模塊的所有文檔,但無法弄清楚。我如何優雅地處理連接錯誤。

這是我得到的(如果資源不可用,並且拒絕連接)錯誤

#Sending subscribe request to 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 
    at errnoException (net.js:904:11) 
    at Object.afterConnect [as oncomplete] (net.js:895:19) 

回答

0

就像in the example in the documentation,你應該處理的錯誤是這樣的:

req.on('error', function(e) { 
    console.log('problem with request: ' + e.message); 
}); 

錯誤或異常在異步操作中不會被更高級別的try/catch捕獲。所以,他們必須像這樣分開處理。

+0

完美!謝謝我只是因爲某種原因錯過了那部分,可能是因爲我只是盲目或者其他。但是,這是完美的,因爲它應該。 – DKhanaf