gpt4 book ai didi

node.js - Nodejs 异常转义 try/catch block

转载 作者:可可西里 更新时间:2023-11-01 17:36:26 25 4
gpt4 key购买 nike

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)

最佳答案

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

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

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

关于node.js - Nodejs 异常转义 try/catch block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30183220/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com