nodejs, trycatch and process.on
Blogs20152015-01-18
nodejs, trycatch and process.on
I have an ExpressJS server as a proxy to delegate HTTP requests from/to various resources of JDK/Cloud/Static servers. When sending several requests at the same time, if the previous request is blocked/fails (e.g. Jetty is down, connection refused), the following requests are pending/fails instead of 200 success. A solution is needed to make each HTTP requests is really independent. My solution is using the following 2 steps:
- npm trycatch module
Trycatch is An asynchronous domain-based exception handler with long stack traces for node.js. It is pretty cool: even the http request fails (connection reset), it still can guaranteed to return back to front-end without lost theresponse handler res. - built-in process on event.
use process.on(‘uncaughtException’) to capture errors, otherwise there will be block in a cascade http requests.
var trycatch = require('trycatch');
var request = require('request');
exports.findAll = function (req, res) {
trycatch(function () {
request.get({
url: rest-api-local-javal-json-call,
headers: req.headers
}).pipe(res);
}, function (err) {
// if failed from dynamic server, use static data instead:
console.log('jetty server is ECONNREFUSED! Use mock-data instead.');
res.sendfile("lib/REST/dummy/all.json");
})
};
// the process.on('uncaughtException') can't be ignored, otherwise the trycatch not work.
process.on('uncaughtException', function (err) {
if (err.code && err.code === 'ECONNREFUSED') {
console.log('--- uncaughtException: rest-api-call-1 ---');
}
else {
console.log('--- uncaughtException: rest-api-call-2 ---');
}
});By using this way, there will be **NO BLOCK** in the node/express proxy server even if some requests fail.
