Nodejs exception escapes the try/catch block

2019-08-14 05:42发布

问题:

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);
}

Thats my code. However, if the resource I am trying to connect isnt available or there is any sort of connection issue the exception escapes my try/catch and gets caught by the unhandled exception handler.

I am totally confused as to why. I looked through all documentation for the http module and can't figure it out. How do I handle connection errors gracefully.

This is the error I get (if the resource isn't available and refuses connection)

    #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:

Just like in the example in the documentation, you should handle errors like this:

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

Errors or exceptions in asynchronous operations will not be caught by a try/catch at a higher level. So, they have to be handled separately like this.



标签: node.js http