rust

Rust error propagation in block expression try like block


I have a function that does something.

In case of any error I need to do addition action. It's nice to wrap everything in block expression and just check the result at the end, like in try block.

Issue is that block expression doesn't need to be async, but removing async makes propagated error jump outside block(result).

What can be convenient alternative for such case?

    async fn main() -> Result<i32, Error> {
        let result: Result<i32, Error> = async {
            do_smth()?;
            do_smth()?;
            do_smth()?;

            Ok(1)
        }
        .await;

        if result.is_err() {
            additional_action();
        };

        result
    }

Solution

  • An immediately-invoked closure provides the same kind of control flow in sync context as an immediately-awaited async block does in async context. This is the idiomatic workaround until try blocks are stabilized.

    fn main() -> Result<i32, Error> {
        let result: Result<i32, Error> = (|| {
            do_smth()?;
            do_smth()?;
            do_smth()?;
    
            Ok(1)
        })();
    
        if result.is_err() {
            additional_action();
        };
    
        result
    }