请求管道上的错误处理 [英] Error handling on request piping
本文介绍了请求管道上的错误处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在nodejs上编写了简单的代理,它看起来像
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)
如何处理此类错误?
推荐答案
查看文档( https://github.com/mikeal/request )你应该可以按照以下几行执行操作:
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
});
这篇关于请求管道上的错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文