簡體   English   中英

如何處理node.js請求中的URI錯誤?

[英]How to handle a URI error in node.js Request?

嘗試簡單地根據請求下載文件。 https://www.npmjs.com/package/request

它工作正常,但是如果url無效,則腳本會崩潰並顯示以下錯誤:無效的URI“ notagoodurl”

如何處理此錯誤並記錄某些內容,並防止整個腳本由於該錯誤而結束? 我認為那是on('error')會​​做的。

//download file
request
  .get(url)
  .on('error', function(err) {
    return err;
  })
  .pipe(
    fs.createWriteStream(destination)
      .on('close', function() {
        message.channel.send(filename + ' added.');
      })
  );

如果您需要解決致命錯誤,則將調用包裝成catch

try {
  //download file
  request
    .get(url)
    .on('error', function(err) {
      console.log('Not a fatal error:', err);
    })
    .pipe(
      fs.createWriteStream(destination)
        .on('close', function() {
          message.channel.send(filename + ' added.');
        })
    );
} catch (err) {
  console.log('Fatal error:', err);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM