Skip to content

Instantly share code, notes, and snippets.

@denmerc
Forked from mausch/gist:3188428
Last active March 6, 2018 04:10
Show Gist options
  • Save denmerc/0c9b6f1e58f716760ebd6f74b3ab0145 to your computer and use it in GitHub Desktop.
Save denmerc/0c9b6f1e58f716760ebd6f74b3ab0145 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")
//another eg
let work a = async {
return
match a with
| 1 -> "Success!"
| _ -> failwith "Darnit"
}
let printResult (res:Choice<'a,System.Exception>) =
match res with
| Choice1Of2 a -> printfn "%A" a
| Choice2Of2 e -> printfn "Exception: %s" e.Message
let callingWorkflow =
async {
let result = work 1 |> Async.Catch
let result2 = work 0 |> Async.Catch
[ result; result2 ]
|> Async.Parallel
|> Async.RunSynchronously
|> Array.iter printResult
}
callingWorkflow |> Async.RunSynchronously
Async.Catch returns a Choice<'T1,'T2>. Choice1Of2 for a successful execution, and the exception thrown for the Choice2Of2.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment