Skip to content

Instantly share code, notes, and snippets.

@therustmonk
Forked from mausch/gist:3188428
Created February 3, 2017 12:51
Show Gist options
  • Save therustmonk/0d09fe1bc77ac211456c4da9a48526a3 to your computer and use it in GitHub Desktop.
Save therustmonk/0d09fe1bc77ac211456c4da9a48526a3 to your computer and use it in GitHub Desktop.
Async exception handling in F#
open System
open System.Net
// exception handling in async using Async.Catch
let fetchAsync (name, url:string) =
async {
let uri = new System.Uri(url)
let webClient = new WebClient()
let! html = Async.Catch (webClient.AsyncDownloadString(uri))
match html with
| Choice1Of2 html -> printfn "Read %d characters for %s" html.Length name
| Choice2Of2 error -> printfn "Error! %s" error.Message
} |> Async.Start
// exception handling in async using regular try/with
let fetchAsync2 (name, url:string) =
async {
let uri = new System.Uri(url)
let webClient = new WebClient()
try
let! html = webClient.AsyncDownloadString(uri)
printfn "Read %d characters for %s" html.Length name
with error -> printfn "Error! %s" error.Message
} |> Async.Start
fetchAsync2 ("blah", "http://asdlkajsdlj.com")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment