【问题标题】:Async Exception Handling in F#F# 中的异步异常处理
【发布时间】:2013-05-20 14:42:15
【问题描述】:

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

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

【问题讨论】:

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


    【解决方案1】:

    返回错误字符串时只需添加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)
    

    【讨论】:

    • 谢谢杰克!有用! :) 为什么您认为 Async.Catch 是一种更好的方法。我认为应该在downloadPage中进行异常处理,不是吗?
    • 我认为Async.Catch 更好,因为:(1)它保留了有关错误的信息......除了 404 之外,还有其他原因可能引发异常,并且有异常而不是“错误" 更容易诊断问题; (2) 使用Choice<_,_> 允许您使用类型系统来强制执行结果和错误的处理路径。
    猜你喜欢
    • 2019-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-14
    • 1970-01-01
    • 2014-04-02
    相关资源
    最近更新 更多