简体   繁体   中英

in Rust how can I dump the result of a panic! returned by join() if it is not a &'static str?

I have a Rust program where I spawn a number of threads and store the JoinHandle s. When I later join the threads that panic! ed, I'm not sure how to retrieve the message that was passed to panic!

Recovering from `panic!` in another thread covers a simple case, but when I applied it to my code it turns out it doesn't work, so I have updated my example:

If I run the following program

fn main() {
    let handle = std::thread::spawn(||panic!(format!("demo {}",1)));
    match handle.join() {
        Ok(_) => println!("OK"),
        Err(b) => println!("Err {:?}", b.downcast_ref::<&'static str>())
    }
}

( rust playground) It prints Err None . I want to access the "demo" message.

Based on the comments, I was able to come up with a working solution ( rust playground ):

fn main() {
    let handle = std::thread::spawn(|| {
        panic!("malfunction {}", 7);
        if true {
            Err(14)
        } else {
            Ok("bacon".to_string())
        }
    });
    match handle.join() {
        Ok(msg) => println!("OK {:?}", msg),
        Err(b) => {
            let msg = if let Some(msg) = b.downcast_ref::<&'static str>() {
                msg.to_string()
            } else if let Some(msg) = b.downcast_ref::<String>() {
                msg.clone()
            } else {
                format!("?{:?}", b)
            };
            println!("{}", msg);
        }
    }
}

which prints malfunction 7 like I want. While this toy example doesn't need all the branches, a more complex piece of code might have some panic! s that give &'static str and others that give String .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM