gpt4 book ai didi

f# - 在 Async.Start 中捕获异常?

转载 作者:行者123 更新时间:2023-12-04 15:31:51 24 4
gpt4 key购买 nike

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

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)

最佳答案

一种方法是使用 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 .

关于f# - 在 Async.Start 中捕获异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38964015/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com