[英]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.