I use Async.Catch to handle exceptions thrown by async workflows:
work
|> Async.Catch
|> Async.RunSynchronously
|> fun x -> match x with
| Choice1Of2 _ -> () // success
| Choice2Of2 ex -> // failure, handle exception
Today I noticed that OperationCanceledExceptions aren't handled by Async.Catch. Instead of getting a Choice from Async.Catch the exception keeps bubbling up until it hits me. I expected the following test to be red, but it's green:
[<Test>]
let ``Async.Catch doesnt work on OperationCancelledExceptions``() =
use cancellationTokenSource = new System.Threading.CancellationTokenSource(1000)
let work = async {
while true do
do! Async.Sleep 100
}
(fun () -> work
|> Async.Catch
|> fun x -> Async.RunSynchronously (x, cancellationToken=cancellationTokenSource.Token)
|> ignore)
|> should throw typeof<System.OperationCanceledException>
Evaluating some exceptions with Async.Catch + Choices + matching and some others using try/catch blocks doesn't seem right... it would look like the following, which is way too complicated. Besides that I wonder what use Async.Catch has, since I have to use a try/catch block anyway...:
[<Test>]
let ``evaluating exceptions of async workflows``() =
use cancellationTokenSource = new System.Threading.CancellationTokenSource(1000)
let work = async {
while true do
do! Async.Sleep 100
}
try
work
|> Async.Catch
|> fun x -> Async.RunSynchronously (x, cancellationToken=cancellationTokenSource.Token)
|> fun x -> match x with
| Choice1Of2 result -> () // success, process result
| Choice2Of2 ex -> () // failure, handle exception
with ex -> () // another failure, handle exception here too
What's the best way to handle exceptions of async workflows? Should I just dump Async.Catch and use try/catch blocks everywhere?