F#中的异步异常处理

时间:2013-05-20 14:42:15

标签: exception-handling f# webclient f#-async

我正在尝试在F#中编写非阻塞代码。我需要下载一个网页,但有时该网页不存在,AsyncDownloadString会抛出异常(404 Not Found)。我尝试了下面的代码,但它没有编译。

我如何处理来自AsyncDownloadString的异常?

let downloadPage(url: System.Uri) = async {
    try
       use webClient = new System.Net.WebClient()
       return! webClient.AsyncDownloadString(url)
    with error -> "Error"
}

我怎么想在这里处理异常?如果抛出错误,我只想返回一个空字符串或带有消息的字符串。

1 个答案:

答案 0 :(得分:16)

只需在返回错误字符串时添加return关键字:

let downloadPage(url: System.Uri) = async {
    try
       use webClient = new System.Net.WebClient()
       return! webClient.AsyncDownloadString(url)
    with error -> return "Error"
}

IMO更好的方法是使用Async.Catch而不是返回错误字符串:

let downloadPageImpl (url: System.Uri) = async {
    use webClient = new System.Net.WebClient()
    return! webClient.AsyncDownloadString(url)
}

let downloadPage url =
    Async.Catch (downloadPageImpl url)