簡體   English   中英

F#中的異步異常處理

[英]Async Exception Handling in F#

我試圖在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"
}

我怎么想在這里處理異常? 如果拋出錯誤,我只想返回一個空字符串或帶有消息的字符串。

只需在return錯誤字符串時添加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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM