2013-05-20 153 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 <_,_>'可以讓你使用類型系統來執行結果和錯誤的處理路徑。 –