#exception #async #sync #panic #ctx #exception-context

asex

Library that helps you to simulate exception without panic in async Rust

3 releases (breaking)

0.3.0 Mar 19, 2022
0.2.0 Mar 17, 2022
0.1.0 Mar 14, 2022

#209 in Simulation

MIT/Apache

13KB
149 lines

as(ync)ex(ception)

Simulate exception without panic in async Rust.

DISCLAIMER: This crate is just to implement my idea. It may not be a good practice.

Check this blog for the main idea.

WARNING: The sync implementation under asex::sync has many unsafe code. Use it as your own risk.

License

This project is distributed under the terms of both the MIT license and the Apache License (Version 2.0).


lib.rs:

Library that helps you to simulate exception without panic in async Rust.

There is an unsync version unsync::ExceptionContext and a sync version sync::ExceptionContext.

Check this blog for the main idea.

Example:

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)
});

Dependencies

~47KB