Catch Unwind Isolates Panicking Work

Wrap risky calls in std::panic::catch_unwind so a panic comes back as an Err payload and the supervisor loop keeps running instead of aborting.

RustResilience

Code

rustsnippet
32 lines
use std::panic;

fn batch(items: &[&str], fail_at: &str) {
    for item in items {
        if *item == fail_at {
            panic!("bad record {item}");
        }
        println!("processed {item}");
    }
}

fn main() {
    let batch_a: &[&str] = &["a", "b", "c"];
    let batch_b: &[&str] = &["x", "boom", "y"];
    let jobs = [(batch_a, "none"), (batch_b, "boom")];

    for (items, fail_at) in jobs {
        // catch_unwind 把 panic 变成 Err 结果:一个任务的崩溃不再带崩整个进程
        match panic::catch_unwind(|| batch(items, fail_at)) {
            Ok(()) => println!("batch done"),
            Err(payload) => {
                let message = payload
                    .downcast_ref::<String>()
                    .cloned()
                    .or_else(|| payload.downcast_ref::<&str>().map(|s| s.to_string()))
                    .unwrap_or_else(|| "opaque payload".to_string());
                println!("isolated: {message}");
            }
        }
    }
    println!("supervisor still alive");
}

What the code does

Catch Unwind Isolates Panicking Work comes down to the functions batch and main.

Repetition is confined to for item in items — the rest of the file is straight-line. A match enumerates the value’s possible shapes, and the compiler rejects any arm you forget.

Applying it

The primary signature is fn batch(items: &[&str], fail_at: &str)

The demo output is labeled (processed, batch done, isolated:); each label names the call that printed it.

There are 1 call inside main — batch — executed top to bottom.

Statements that matter

Err(payload) => {
    let message = payload
        .downcast_ref::<String>()
        .cloned()
        .or_else(|| payload.downcast_ref::<&str>().map(|s| s.to_string()))
        .unwrap_or_else(|| "opaque payload".to_string());
    println!("isolated: {message}");
}
fn batch(items: &[&str], fail_at: &str) {
    for item in items {
        if *item == fail_at {
            panic!("bad record {item}");
        }
        println!("processed {item}");
    }
}

Interactive Tools for This Topic

FAQ

What does Catch Unwind Isolates Panicking Work print when run?
Execute the whole file; each printed line is prefixed with a label like `processed`, `batch done`, `isolated:`.