Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use panic::catch_unwind with asynchronous code?

When working with synchronous code, I can use panic::catch_unwind like this:

#[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(())
}

How do I do the same when working with async code that is executed inside the catch_unwind block? I can't figure out how to run the block while also being able to run some code after the block and finally assert the result.

This is what I have so far:

#[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(())
}
like image 282
Oskar Persson Avatar asked Apr 15 '26 23:04

Oskar Persson


1 Answers

I would not attempt to use them directly. Instead, use FutureExt::catch_unwind and 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(())
}
like image 186
Shepmaster Avatar answered Apr 18 '26 16:04

Shepmaster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!