Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async Exception Handling in F#

I am trying to write non-blocking code in F#. I need to download a webpage, but sometime that webpage doesn't exist and an exception is thrown (404 Not Found) by AsyncDownloadString. I tried the code below but it doesn't compile.

How could I handle exception from AsyncDownloadString?

let downloadPage(url: System.Uri) = async {
    try
       use webClient = new System.Net.WebClient()
       return! webClient.AsyncDownloadString(url)
    with error -> "Error"
}

How am I suppose to handle exception here? If an error is thrown, I simply want to return an empty string or a string with a message in it.

like image 563
Martin Avatar asked May 20 '13 14:05

Martin


1 Answers

Just add the return keyword when you return your error string:

let downloadPage(url: System.Uri) = async {
    try
       use webClient = new System.Net.WebClient()
       return! webClient.AsyncDownloadString(url)
    with error -> return "Error"
}

IMO a better approach would be to use Async.Catch instead of returning an error string:

let downloadPageImpl (url: System.Uri) = async {
    use webClient = new System.Net.WebClient()
    return! webClient.AsyncDownloadString(url)
}

let downloadPage url =
    Async.Catch (downloadPageImpl url)
like image 155
Jack P. Avatar answered Sep 28 '22 07:09

Jack P.