我有此代碼可以使用API從第三方網站下載新聞源。其設置爲每5秒運行一次,並引發可能發生的任何新聞交易。問題似乎是在沒有發生新交易的情況下。通過添加process.on('未捕獲的異常',函數(錯誤){console.log(「hmph」)})cron作業能夠在5秒後繼續,所以我被誘惑將它保留爲是;但是,我添加了console.log(「hmph」),現在我很困惑。如何在http.get響應中處理未捕獲的異常
第一次,控制檯會寫入hmph。 5秒後它會寫 hmph hmph
等等。我知道我必須錯過一些東西,但我不太確定它是什麼。我試着在else語句中執行request.end(),但錯誤仍然激發。
沒有process.on( '未捕獲的......')拋出的錯誤是:
events.js:71 throw arguments[1]; // Unhandled 'error' event ^ Error: Parse Error at Socket.socketOnData (http.js:1367:20) at TCP.onread (net.js:403:27)
與proccess.on( '未捕獲...')內的console.log(誤差) :
{ [Error: Parse Error] bytesParsed: 161, code: 'HPE_INVALID_CONSTANT' }
我該如何正確處理這個錯誤?
縮寫代碼:
var job = new cronJob('*/5 * * * * *', function(){
var request = http.get({
host: 'www.example.com',
path: '/news_feed?apicode=myapicode',
port: 80,
headers: { 'accept-encoding': 'gzip' }
})
request.on('response', function(response){
if (response.statusCode == 200){
// gunzip response, save response to mongodb
}
else
{
// here is where the error is occuring
process.on('uncaughtException',function(error){
console.log(error);
console.log("hmph");
}
});
}, null, true);
我很感謝您的回答;然而,我已經試過這樣做了,我得到:events.js:71 throw arguments [1]; //未處理的 '錯誤' 事件 ^ 錯誤:在Socket.socketOnData解析錯誤 (http.js:1367:20) 在TCP.onread(net.js:403:27) – thtsigma
,你一定要綁定我在同一個地方說過嗎?你不會把錯誤放在響應回調中,就像你有你的uncaughtException處理程序 – loganfsmyth
是的,我已經檢查過了,它在同一個地方。這是完整的代碼W /你的建議。 http://pastebin.com/PTu7cA8s – thtsigma