#exception #sync #async #panic #context #global

asynx

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

1 unstable release

0.1.0 Apr 25, 2022

#380 in Simulation

MIT/Apache

22KB
217 lines

ASYNc eXecption

Simulate exception without panic in async Rust.

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

Use in your project:

[dependencies]
asynx = "0.1"

Check docs.rs docs for usage.

You can use it in no_std environment by

[dependencies]
asynx = { version = "0.1", default-features = false }

which will disable global implementation.

Check this blog for the main idea.

WARNING: The sync implementation under asynx::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.

You can also define the context as a static variable so that you don't have to pass them through function argument, using global::ExceptionContext.

Check this blog for the main idea.

Example:

type ExcptCtx = asynx::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()
        .catch(|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