在Async.Start中捕获异常?

时间:2016-08-15 22:32:48

标签: f#

我有以下代码。我想在不阻塞主线程的情况下运行。

let post () = .....
try
    let response = post ()
    logger.Info(response.ToString())
with 
| ex -> logger.Error(ex, "Exception: " + ex.Message)

所以我将代码更改为以下内容。但是,如何在post

中捕获异常
let post = async { 
   ....
   return X }
try
    let response = post |> Async.StartChild
    logger.Info(response.ToString())
with 
| ex -> logger.Error(ex, "Exception: " + ex.Message)

2 个答案:

答案 0 :(得分:2)

一种方法是在调用工作流程中使用Async.Catch。给出了几个函数(一次性“异步”函数和一些与结果一起使用的函数):

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

One can use Async.Catch

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返回Choice<'T1,'T2>Choice1Of2表示执行成功,Choice2Of2抛出异常。

答案 1 :(得分:1)

您还可以将try / catch放在async块中

let post = async { .... }
async {
  try
    let! response = post
    logger.Info(response.ToString())
  with 
  | ex -> logger.Error(ex, "Exception: " + ex.Message)
} |> Async.Start