F#:处理网络例外

问题描述:

我是编程新手,F#是我的第一语言。F#:处理网络例外

这里是我的代码的相关片段:

let downloadHtmlToDiskAsync (fighterHtmlDirectory: string) (fighterBaseUrl: string) (fighterId: int) = 
    let fighterUrl = fighterBaseUrl + fighterId.ToString() 
    try 
     async { 

      let! html = fetchHtmlAsync fighterUrl 
      let fighterName = getFighterNameFromPage html 

      let newTextFile = File.Create(fighterHtmlDirectory + "\\" + fighterId.ToString("00000") + " " + fighterName.TrimEnd([|' '|]) + ".html") 
      use file = new StreamWriter(newTextFile) 
      file.Write(html) 
      file.Close() 
     } 
    with 
     :? System.Net.WebException -> async {File.AppendAllText("G:\User\WebScraping\Invalid Urls.txt", fighterUrl + "\n")} 

let downloadFighterDatabase (directoryPath: string) (fighterBaseUrl: string) (beginningFighterId: int) (endFighterId: int) = 
    let allFighterIds = [for id in beginningFighterId .. endFighterId -> id] 
    allFighterIds 
    |> Seq.map (fun fighterId -> downloadHtmlToDiskAsync directoryPath fighterBaseUrl fighterId) 
    |> Async.Parallel 
    |> Async.RunSynchronously 

我一直在使用F#交互式测试功能fetchHtmlAsync和getFighterNameFromPage。他们都很好。

当我构建和运行解决方案,但是,我得到了以下错误消息:

An unhandled exception of type 'System.Net.WebException' occurred in FSharp.Core.dll Additional information: The remote server returned an error: (404) Not Found.

出了什么问题?我应该做什么改变?

将您的trywith放入async之内。

let downloadHtmlToDiskAsync (fighterHtmlDirectory: string) (fighterBaseUrl: string) (fighterId: int) = 
    let fighterUrl = fighterBaseUrl + fighterId.ToString() 
    async { 
     try 
      let! html = fetchHtmlAsync fighterUrl 
      let fighterName = getFighterNameFromPage html 

      let newTextFile = File.Create(fighterHtmlDirectory + "\\" + fighterId.ToString("00000") + " " + fighterName.TrimEnd([|' '|]) + ".html") 
      use file = new StreamWriter(newTextFile) 
      file.Write(html) 
      file.Close() 
     with 
      :? System.Net.WebException -> File.AppendAllText("G:\User\WebScraping\Invalid Urls.txt", fighterUrl + "\n") 
    } 
+0

笑... 6秒时:d – Carsten 2015-03-31 17:20:40

+0

哈哈是啊,我只是评论同样的事情在你的答案 – albertjan 2015-03-31 17:21:36

+1

谢谢,albertjan!事实证明,我是一个白痴......我最初是按照你的方式编写我的代码,但因为我忘记重建我的解决方案,所以我一直收到一条错误消息,这促使我开始做出不必要和不准确的更改。现在我刚刚重建,一切都很好。再次感谢你的帮助。 :-) – 2015-03-31 17:44:42