2017-02-22 92 views
0

我使用像這樣的工作時間,以便如何處理第三方的Node.js庫的斷言錯誤

let request = require('request'); 
request(SOME_URL, { proxy }, function (error, response, body) { 
    if (error) { 
     console.log('Error: ' + error); 
     return; 
    } 
    // my actual code here that usually runs 
}); 

98%Node.js的請求模塊的請求,但有時我使用一個代理,行動起來,這會導致一些奇怪的行爲。我的代碼將沿着精細哼唱,直到它突然停止與以下堆棧跟蹤:

assert.js:85 
    throw new assert.AssertionError({ 
^

AssertionError: 542 == 0 
    at ClientRequest.onConnect (/home/stephen/apps/my-cool-app/node_modules/tunnel-agent/index.js:159:14) 
    at ClientRequest.g (events.js:291:16) 
    at emitThree (events.js:116:13) 
    at ClientRequest.emit (events.js:194:7) 
    at Socket.socketOnData (_http_client.js:395:11) 
    at emitOne (events.js:96:13) 
    at Socket.emit (events.js:188:7) 
    at readableAddChunk (_stream_readable.js:176:18) 
    at Socket.Readable.push (_stream_readable.js:134:10) 
    at TCP.onread (net.js:548:20) 

現在,我想那種預料在回調中返回的任何錯誤。但是這並沒有發生,所以我無法在那裏適當地處理它。

我想在一個try/catch塊圍繞這個,如下所示:

try { 
    request(SOME_URL, { proxy }, function (error, response, body) { 
     if (error) { 
      console.log('Error: ' + error); 
      return; 
     } 
     // my actual code here that usually runs 
    }); 
} catch (err) { 
    console.log('Caught error: ' + err); 
} 

但是,這也不能正常工作 - 我仍然得到Asse田和我的程序停止。

所以,我的問題是:如何優雅地處理這個問題?如果我遇到這個AssertionError我想取消(或忽略)請求並繼續進行,不會讓我的程序崩潰。

+0

你可能就需要編輯的庫來修復它或控制的條件,因此嗟這一說法。拋出異步回調(除了自動封裝在try/catch中的promise外)是不好的行爲,因爲它不能被更高級別的代碼捕獲。你可能可以通過重新定義它們在模塊中使用的任何斷言函數來解決它,而不是以其他方式觸摸代碼。 – jfriend00

+0

我遇到了與您遇到的完全相同的問題。我同意上面的jfriend00,解決此問題的唯一好方法是實際修復庫代碼並妥善處理。我更改了tunnel-agent中的代碼以返回錯誤,而不是執行此斷言。 –

回答

0

這可能是處理這些不受歡迎的主張的唯一途徑:

process.on('uncaughtException', err => { 

    if (err.name === 'AssertionError') { 
     // handle the assertion here or just ignore it.. 

    } 


});