Mar*_*tin 8 f# webclient exception-handling f#-async
我试图在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"
}
Run Code Online (Sandbox Code Playgroud)
我怎么想在这里处理异常?如果抛出错误,我只想返回一个空字符串或带有消息的字符串.
Jac*_* P. 17
只需return在返回错误字符串时添加关键字:
let downloadPage(url: System.Uri) = async {
try
use webClient = new System.Net.WebClient()
return! webClient.AsyncDownloadString(url)
with error -> return "Error"
}
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2932 次 |
| 最近记录: |