13

我正在尝试在 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"
}

我应该如何在这里处理异常?如果抛出错误,我只想返回一个空字符串或一个包含消息的字符串。

4

1 回答 1

22

只需在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)
于 2013-05-20T14:51:59.450 回答