I have written sample node application to handle error data such as database connection error, port conflict error, process uncaught exception. When error occurrs an http request is made to process the error. In such case when node process exist abnormally, I am able to handle exist in process.on('exit')
function but I am not able to send http request, the process is exiting quickly.
Can any one suggest how to send http request and get the response on Node.js before process exit. Below is the sample code for sending http request on process exists
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);
});
})