使用同步代码时,我可以这样使用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(())
}
Run Code Online (Sandbox Code Playgroud)
使用在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(())
}
Run Code Online (Sandbox Code Playgroud)
我不会尝试直接使用它们。相反,使用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(())
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
878 次 |
| 最近记录: |