F#:处理Web异常

时间:2015-03-31 17:15:40

标签: asynchronous f# system.net.webexception

我是编程新手,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#Interactive测试了函数fetchHtmlAsync和getFighterNameFromPage。他们都工作正常。

但是,当我构建并运行解决方案时,我收到以下错误消息:

  

未处理的类型' System.Net.WebException'发生在FSharp.Core.dll中   附加信息:远程服务器返回错误:(404)Not Found。

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

1 个答案:

答案 0 :(得分:3)

try with放入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")
    }