gpt4 book ai didi

rust - 如何在异步代码中使用 panic::catch_unwind?

转载 作者:行者123 更新时间:2023-12-03 11:34:06 24 4
gpt4 key购买 nike

使用同步代码时,我可以使用 panic::catch_unwind像这样:

#[actix_rt::test]
async fn test_sync() -> Result<(), Error> {
println!("before catch_unwind");
let sync_result = panic::catch_unwind(|| {
println!("inside sync catch_unwind");
panic!("this is error")
});
println!("after catch_unwind");

assert!(sync_result.is_ok());

Ok(())
}
在处理在 catch_unwind 中执行的异步代码时,我该如何做同样的事情?堵塞?我无法弄清楚如何运行块,同时还能够在块之后运行一些代码并最终断言结果。
这是我到目前为止:
#[actix_rt::test]
async fn test_async() -> Result<(), Error> {
println!("before catch_unwind");
let async_result = panic::catch_unwind(|| async {
println!("inside async catch_unwind");
panic!("this is error")
}).await;
println!("after catch_unwind");

assert!(async_result.is_ok());

Ok(())
}

最佳答案

不会 尝试直接使用它们。相反,使用 FutureExt::catch_unwind StreamExt::catch_unwind .

use futures::FutureExt; // 0.3.5

#[tokio::test]
async fn test_async() -> Result<(), Box<dyn std::error::Error>> {
println!("before catch_unwind");

let may_panic = async {
println!("inside async catch_unwind");
panic!("this is error")
};

let async_result = may_panic.catch_unwind().await;

println!("after catch_unwind");

assert!(async_result.is_ok());

Ok(())
}

关于rust - 如何在异步代码中使用 panic::catch_unwind?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63159442/

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