Nodejs异常会转义try / catch块 [英] Nodejs exception escapes the try/catch block

查看:797
本文介绍了Nodejs异常会转义try / catch块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我完全不知道为什么。我查看了http模块的所有文档,但无法弄明白。如何正常处理连接错误。

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)


推荐答案

就像在文档示例中,您应该处理如下错误:

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

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

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.

这篇关于Nodejs异常会转义try / catch块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆