Reputation: 81
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);
});
})
Upvotes: 2
Views: 1688
Reputation: 11
Hit on same problem, according to the doc https://nodejs.org/api/process.html#process_event_exit
"Event: 'exit' Listener functions must only perform synchronous operations." make it hard to send request to other system.
A possible workaround method is to to execute another script/cmd, eg.
import exec from 'child_process'
mocha.run(failures => {
process.on('exit', () => {
exec.execSync(some cmd, function (error, stderr) {
if (error) {
throw (error);
}
}
}
Upvotes: 1
Reputation: 6801
In process.on('exit', [fn])
you cannot do any asynchronous action as stated in the docs. However, this is an anti-pattern also discovered in many libraries.
You need to rely on process.on('uncaughtException', [fn])
or any signal handlers like SIGTERM
.
Upvotes: 0