2013-05-20 156 views
5

我试图在F#中编写非阻塞代码。我需要下载一个网页,但有时网页不存在,AsyncDownloadString引发异常(404 Not Found)。我尝试了下面的代码,但它不能编译。F#中的异步异常处理

我怎样才能处理来自AsyncDownloadString的异常?

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

回答

11

只需添加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) 
+0

谢谢杰克!有用! :)为什么你认为Async.Catch是一个更好的方法。我会认为异常处理应该在downloadPage中完成,不是吗? – Martin

+2

我认为'Async.Catch'更好,因为:(1)它保留有关错误的信息......还有其他原因可能会抛出一个异常,除了404,并且有异常而不是“错误”可以更容易诊断问题; (2)使用'Choice <_,_>'可以让你使用类型系统来执行结果和错误的处理路径。 –