How to properly handle a tokio::try_join! if one of the tasks panics and cleanly abort?

Viewed 40

For the two async functions that I am passing to my try_join!(), let's say there's 3 ways that they could panic.

I'm trying to use a set_hook to catch the errors but I'm not sure how to do a match statement on the panics so I can display a custom error message for each of the ways that they can panic. It looks like set_hook takes a Box(Any) (?), so I was wondering if there was a way to check the type of Error. Basically I just don't want to do regex on the ErrString.

I'm also not sure what the best way to abort the runtime within each match branch. I'm currently using std::process::exit(0).

code looks like:

set_hook(Box::new(|panic_info| {
            println!("Thread panicked! {}", panic_info);
            // std::process::exit(0);
        }));

let (result1, result2) = tokio::try_join!(func1, func2); // code that could panic

I want to be able to do something like

set_hook(Box::new(|panic_info| {
            match panic_info {
                panic_type_1 => { println!("X was invalid, please try using valid X") }
                panic_type_2 => { println!("Y was invalid, please try using valid Y") }
                panic_type_3 => { println!("Z was invalid, please try using valid Z") }
                _ => { println!("Something else happened: {}", panic_info) }
            }
        }));

let (result1, result2) = tokio::try_join!(func1, func2); // code that could panic
1 Answers

Don't bother with set_hook. The future that tokio::task::spawn* returns resolves to a Result with a JoinError type, which has a [try_]into_panic to get the boxed object that was passed to panic.

The panic message is stored as a Box<dyn Any> which has tons of methods for downcasting it into various types.

Related