1

我有此代碼可以使用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); 

回答

3

你提出一個要求每一次,你要綁定一個新uncaughtException處理程序,因此發送的第一個請求時,你綁定的第一個,當它失敗它將打印錯誤,然後在下一個請求中添加另一個處理程序,並在第一個和第二個處理程序都運行時失敗。

檢查錯誤,並在這裏討論這種類型的錯誤:https://github.com/joyent/node/issues/3354看起來你連接到的服務器可能會做一些奇怪的事情。對你來說最簡單的解決方案可能就是現在使用uncaughtException處理程序。也就是說,這不是理想的,你不應該把它作爲解決這樣的未來問題的一般解決方案。

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 
    } 
    }); 
}, null, true); 

process.on('uncaughtException',function(error){ 
    console.log(error); 
    console.log("hmph"); 
}); 
+0

我很感謝您的回答;然而,我已經試過這樣做了,我得到:events.js:71 throw arguments [1]; //未處理的 '錯誤' 事件 ^ 錯誤:在Socket.socketOnData解析錯誤 (http.js:1367:20) 在TCP.onread(net.js:403:27) – thtsigma

+0

,你一定要綁定我在同一個地方說過嗎?你不會把錯誤放在響應回調中,就像你有你的uncaughtException處理程序 – loganfsmyth

+0

是的,我已經檢查過了,它在同一個地方。這是完整的代碼W /你的建議。 http://pastebin.com/PTu7cA8s – thtsigma

相關問題