【发布时间】:2017-08-04 13:16:47
【问题描述】:
我编写了示例节点应用程序来处理错误数据,例如数据库连接错误、端口冲突错误、处理未捕获的异常。当发生错误时,会发出一个 http 请求来处理错误。在这种情况下节点进程异常存在,我可以在process.on('exit')函数中处理存在但我无法发送http请求,进程正在快速退出。
任何人都可以建议如何在进程退出之前发送 http 请求并在 Node.js 上获取响应。下面是在存在的进程上发送http请求的示例代码
var http = require('http');
var errorData=null;
var sendErrorReport = function(data,callback){
var options = {
host : connection.host,
path : "/api/errorReport",
port : connection.port,
method : 'POST',
timeout: connection.timeInterval,
headers:{
'Content-Type':'application/json',
'Content-Length': Buffer.byteLength(data)}
}
var request = http.request(options,function(response){
callback(response);
});
request.on('error',function(err){
console.log("On Error");
callback(err);
});
request.on('timeout', function(err){console.log("On Timeout");
callback(err);});
request.write(data);
request.end();
}
process.on('uncaughtException', function ( err ) {
errorData = err;
});
process.on('exit',function(code){
sendErrorReport(errorData,function(err,res){
console.log(res);
});
})
【问题讨论】:
-
如果你处理
SIGINT或uncaughtException事件,你可以在请求的回调中调用process.exit。它应该挂起,直到你调用.exit()函数。 -
在某些情况下我需要在未抛出未捕获的异常时处理进程退出。
标签: node.js http process request exit