3 个版本 (破坏性)
0.3.0 | 2022 年 3 月 19 日 |
---|---|
0.2.0 | 2022 年 3 月 17 日 |
0.1.0 | 2022 年 3 月 14 日 |
#221 in 模拟
13KB
149 行
as(ync)ex(ception)
在异步 Rust 中模拟异常而不使用 panic
。
免责声明:此 crate 仅用于实现我的想法。它可能不是最佳实践。
查看 此博客 了解主要想法。
警告:在 asex::sync
下的同步实现有许多不安全代码。使用时请自行承担风险。
许可证
本项目根据 MIT 许可证和 Apache 许可证(版本 2.0)的条款进行分发。
lib.rs
:
一个帮助您在异步 Rust 中模拟异常而不使用 panic
的库。
存在一个非同步版本 unsync::ExceptionContext 和一个同步版本 sync::ExceptionContext。
查看 此博客 了解主要想法。
示例
type ExcptCtx = asex::unsync::ExceptionContext<String>;
async fn perform(ctx: &ExcptCtx, success: bool) -> String {
if success {
"success".to_string()
} else {
ctx.throw("failed".to_string()).await
}
}
tokio_test::block_on(async {
let r = ExcptCtx::new()
.catching(|ctx| async move {
assert_eq!("success".to_string(), perform(ctx, true).await);
perform(ctx, false).await;
unreachable!() // The previous statement throws an exception.
})
.await;
assert_eq!(Err("failed".to_string()), r)
});
依赖项
~46KB