Nodejs异常会转义try / catch块

时间:2015-05-12 06:19:42

标签: node.js http

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并被未处理的异常处理程序捕获。

我对为什么感到困惑。我查看了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)

1 个答案:

答案 0 :(得分:1)

就像in the example in the documentation一样,你应该处理这样的错误:

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

异步操作中的错误或异常不会被更高级别的try / catch捕获。因此,它们必须像这样单独处理。