I am using npm request module to forward an incoming request to another server as:
app.get("/somepath", function(req, res) {
var url = proxySetting.global.url + req.url;
req.pipe(request(url)).pipe(res);
});
Here: proxySetting.global.url == http://localhost:4000
Now when i forward incoming request like this to target server, if the target server(localhost:4000) is down or the request is hanged on target server.
There will be an error like ECONNREFUSED or hangup error.
Tried catching these error using domain module like below
var d = domain.create();
d.on("error", function(err) {
console.log("Error occoured while forwarding request");
console.log(err);
res.status(500).send("Error occoured while forwarding request");
});
d.run(function() {
req.pipe(request(url)).pipe(res);
});
Tried to catch error event in several combination
var request = require("request");
module.exports = function(proxySetting) {
return function(req, res, next) {
var url = proxySetting.global.url + req.url;
url = url.replace(/([^:]\/)\/+/g, "$1") // replacing multiple slashes with one
console.log("Forwarding request to: " + url);
function errorHandler(err) {
console.log("Error occoured while forwarding request");
console.log(err);
res.status(500).send("Error occoured while forwarding request");
}
req.on("error", errorHandler);
res.on("error", errorHandler);
req.pipe(request(url).on("error",errorHandler)).pipe(res);
};
};
but still the exception is thrown to the process and server crashed One way i am doing now is
process.on('uncaughtException', function(err) {
console.log("Some unhandled error occoured");
console.log(err);
console.log("Stopping server");
process.exit(1);
});
But i think catch uncaughtException and handle is not a proper solution