我正在尝试构建弹性和容错服务,作为测试,我故意导致它在 try-catch 块之外使用未定义的变量崩溃。
我通过nodejs http客户端在本地调用此服务,首先我故意导致错误,然后我继续调用该服务。
第一次错误是 ECONNRESET
{
"code": "ECONNRESET",
"message": "socket hang up",
"stack": "Error: socket hang up\n at createHangUpError (_http_client.js:323:15)\n at Socket.socketOnEnd (_http_client.js:426:23)\n at Socket.emit (events.js:203:15)\n at endReadableNT (_stream_readable.js:1145:12)\n at process._tickCallback (internal/process/next_tick.js:63:19)"
}
第二次调用相同的服务返回ECONNREFUSED
{
"code": "ECONNREFUSED",
"message": "connect ECONNREFUSED 172.20.0.4:3000",
"stack": "Error: connect ECONNREFUSED 172.20.0.4:3000\n at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1106:14)"
}
微服务 - 故意错误的代码
function getEmployee() {
return new Promise(function (resolve, reject) {
let sql = "SELECT * FROM employee";
db.query(sql, function(error, result){
console.log(a); // undefined var
try {
if(error) {
reject({status: 500, result: error});
} else {
resolve({status: 200, result: result});
}
} catch(err) {
reject({status: 500, result: err});
}
});
});
};
调用微服务端点的代码
function getEmployee() {
return new Promise(function (resolve, reject) {
http.request({
method: "GET",
hostname: "localhost",
port: 3000,
path: "/employees"
}, function(response){
let buffers = [];
response.on("data", buffers.push.bind(buffers));
response.on("end", function(){
let data = JSON.parse(Buffer.concat(buffers).toString());
response.statusCode == 200 ? resolve(data) : reject(data);
});
}).on("error", reject).end();
});
};
问题是,我如何处理 nodejs 服务器从错误中恢复以及对该端点或其他端点的后续调用?