← 中文资源

简体中文版本

catch_unwind 隔离 panic 任务

catch_unwind 把 panic 转成携带载荷的 Err:批处理里单个任务崩溃不会带崩整个进程;panic 信息默认仍会经 hook 打到 stderr,隔离但不静音。

阅读英文原文

实现说明

catch_unwind 隔离 panic 任务以函数 batch、main为骨架。 循环只出现在 for item in items,它的每次迭代处理一个元素。match 把每种情况写明白;漏写一个就编译不过。

使用要点

  • 直接运行文件,输出会带上标签,比如 processed、batch done、isolated:——输出的每一行都能指回产生它的那次调用。
  • 运行整个文件:main 会依次驱动 batch。

常见问题

运行「catch_unwind 隔离 panic 任务」会打印什么?

运行文件本身,processed、batch done、isolated: 这些前缀各对应一段演示逻辑。

签名一览:fn batch(items: &[&str], fail_at: &str)

核心语句

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}");
    }
}

代码示例

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");
}