[英]Error handling on request piping
我在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 );
});
如果遠程主機可用,它可以正常工作,但如果遠程主機不可用,則整個節點服務器會因未處理的異常而崩潰
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 ),您應該可以執行以下操作:
您可以根據請求使用可選的回調參數,例如:
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 );
});
或者,您可以使用以下內容捕獲未捕獲的異常:
process.on('uncaughtException', function(err){
console.error('uncaughtException: ' + err.message);
console.error(err.stack);
process.exit(1); // exit with error
});
如果您發現ECONNREFUSED的未捕獲異常,請確保重新啟動您的進程。 我在測試中看到,如果忽略異常並且只是嘗試重新連接,套接字就會變得不穩定。
這是一個很棒的概述: http : //shapeshed.com/uncaught-exceptions-in-node/
我最終使用“forever”工具重啟我的節點進程,使用以下代碼:
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
}
您應該嘗試阻止ECONNREFUSED異常變為未被捕獲:
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
}))
.on('error', err => {
const msg = 'Error on connecting to the webservice.';
console.error(msg, err);
res.status(500).send(msg);
})
.pipe( res );
});
如果你得到一個實際的未捕獲異常,那么你應該讓應用程序死掉。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.