Recover Thread Panics From JoinError

Join a panicking worker and recover its payload: JoinError::is_panic plus into_panic downcasts the boxed Any back to the message the thread panicked with.

RustResilience

Code

rustsnippet
32 lines
use std::thread;

fn main() {
    // 正常返回的 worker:join 得到 Ok
    let healthy = thread::spawn(|| 40 + 2);
    println!("healthy worker returned {:?}", healthy.join());

    // panic 的 worker:join 得到 Err(JoinError)
    let crashing = thread::spawn(|| {
        panic!("worker cache corrupted");
    });

    match crashing.join() {
        Ok(v) => println!("unexpected return {v:?}"),
        Err(err) => {
            if !err.is_panic() {
                println!("not a panic");
                return;
            }
            // into_panic 取回 Box<dyn Any + Send>,按真实载荷类型下探
            let payload = err.into_panic();
            let message = if let Some(s) = payload.downcast_ref::<&'static str>() {
                (*s).to_string()
            } else if let Some(s) = payload.downcast_ref::<String>() {
                s.clone()
            } else {
                String::from("opaque panic payload")
            };
            println!("recovered: {message}");
        }
    }
}

The two joins

thread::spawn(|| 40 + 2) joins as Ok, so the first printed line is healthy worker returned Ok(42). The second worker calls panic!("worker cache corrupted"); joining it yields Err(JoinError), and err.is_panic() distinguishes a panic from other join failures before anything is unpacked. (The panic’s own report goes to stderr through the default hook; the recovered message below is stdout.)

Recovering the payload

healthy worker returned Ok(42)
recovered: worker cache corrupted

err.into_panic() returns the thread’s payload as Box<dyn Any + Send>, and the if let chain downcasts it by real type: &'static str first (the payload type panic! produces for a string literal), then String, else the opaque fallback String::from("opaque panic payload"). panic! with a literal hits the first branch, so the printed message is the thread’s own. The unexpected return and not a panic strings sit in arms this run never reaches — they document the shapes the code can meet, not what printed.

The line that pulls the box out

let payload = err.into_panic();

After this call the JoinError is consumed — recovering the payload is a one-way door, which is why the downcast chain tries every plausible type in one place.

Interactive Tools for This Topic

FAQ

What does Recover Thread Panics From JoinError print when run?
The script runs standalone; its 4 labeled outputs include `healthy worker returned`, `unexpected return`, `not a panic`.