Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
60
rated 0 times [  64] [ 4]  / answers: 1 / hits: 20330  / 11 Years ago, mon, november 25, 2013, 12:00:00

I wrote simple proxy on nodejs and it looks like



var request = require( 'request' );
app.all( '/proxy/*', function( req, res ){
req.pipe( request({
url: config.backendUrl + req.params[0],
qs: req.query,
method: req.method
})).pipe( res );
});


It works fine if remote host is available, but if remote host is unavailable the whole node server crashes with unhandled exception



stream.js:94                                               
throw er; // Unhandled stream error in pipe.
^
Error: connect ECONNREFUSED
at errnoException (net.js:901:11)
at Object.afterConnect [as oncomplete] (net.js:892:19)


How can I handle such errors?


More From » node.js

 Answers
2

Looking at the docs (https://github.com/mikeal/request) you should be able to do something along the following lines:



You can use the optional callback argument on request, for example:



app.all( '/proxy/*', function( req, res ){
req.pipe( request({
url: config.backendUrl + req.params[0],
qs: req.query,
method: req.method
}, function(error, response, body){
if (error.code === 'ECONNREFUSED'){
console.error('Refused connection');
} else {
throw error;
}
})).pipe( res );
});


Alternatively, you can catch an uncaught exception, with something like the following:



process.on('uncaughtException', function(err){
console.error('uncaughtException: ' + err.message);
console.error(err.stack);
process.exit(1); // exit with error
});

[#74076] Saturday, November 23, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
elmer

Total Points: 432
Total Questions: 96
Total Answers: 107

Location: Jordan
Member since Wed, Jun 17, 2020
4 Years ago
;