F#中的异步异常处理

Mar*_*tin 8 f# webclient exception-handling 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"
}
Run Code Online (Sandbox Code Playgroud)

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

Jac*_* P. 17

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

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

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)
Run Code Online (Sandbox Code Playgroud)

  • 我认为`Async.Catch`更好,因为:(1)它保留了有关错误的信息......还有其他原因除了404之外可能抛出异常,而异常而不是"错误"使得诊断更容易问题; (2)使用`Choice <_,_>`允许您使用类型系统来强制执行结果和错误的处理路径. (3认同)