请求pipe道上的error handling

我写了nodejs上的简单代理,看起来像

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 ); }); 

如果远程主机可用,它工作正常,但如果远程主机不可用,则整个节点服务器崩溃,并发生未处理的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) 

我怎样才能处理这样的错误?

看看文档( https://github.com/mikeal/request )你应该能够做一些事情,沿着以下几行:

您可以根据请求使用可选的callback参数,例如:

 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 ); }); 

或者,您可以捕获未捕获的exception,如下所示:

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

如果您捕获ECONNREFUSED的未捕获exception,请确保重新启动您的进程。 我在testing中看到,如果您忽略exception并简单地尝试重新连接,则套接字变得不稳定。

这里有一个很好的概述: http : //shapeshed.com/uncaught-exceptions-in-node/

我结束了使用“永远”的工具来重新启动我的节点进程,用下面的代码:

 process.on('uncaughtException', function(err){ //Is this our connection refused exception? if( err.message.indexOf("ECONNREFUSED") > -1 ) { //Safer to shut down instead of ignoring //See: http://shapeshed.com/uncaught-exceptions-in-node/ console.error("Waiting for CLI connection to come up. Restarting in 2 second..."); setTimeout(shutdownProcess, 2000); } else { //This is some other exception.. console.error('uncaughtException: ' + err.message); console.error(err.stack); shutdownProcess(); } }); //Desc: Restarts the process. Since forever is managing this process it's safe to shut down // it will be restarted. If we ignore exceptions it could lead to unstable behavior. // Exit and let the forever utility restart everything function shutdownProcess() { process.exit(1); //exit with error }