panic any Re-raises Custom Payloads
Unwind with typed payloads using std::panic::panic_any, then recover the original value via downcast so non-string error data survives the panic.
Code
use std::panic::{self, AssertUnwindSafe};
#[derive(Debug)]
struct CorruptOffset {
index: usize,
expected: usize,
}
fn parse_frame(data: &[u8], offset: usize) -> Result<u32, CorruptOffset> {
if offset + 4 > data.len() {
// 抛出结构化载荷而不是字符串:恢复方可以拿到具体字段
panic::panic_any(CorruptOffset { index: offset, expected: data.len() });
}
Ok(u32::from_be_bytes(data[offset..offset + 4].try_into().unwrap()))
}
fn main() {
let data = [0x00, 0x00, 0x00, 0x2a];
// catch_unwind 隔离 panic;AssertUnwindSafe 因为闭包持有可变借用
let result = panic::catch_unwind(AssertUnwindSafe(|| parse_frame(&data, 2)));
// downcast_ref 还原结构化载荷:字符串 panic 做不到这一点
match result {
Ok(value) => println!("parsed: {value}"),
Err(payload) => {
if let Some(err) = payload.downcast_ref::<CorruptOffset>() {
println!("recovered struct: index={} expected={}", err.index, err.expected);
} else if let Some(msg) = payload.downcast_ref::<&str>() {
println!("recovered string: {msg}");
} else {
println!("unknown payload type");
}
}
}
println!("execution continues after recovery");
}How it works
Everything that moves lives in the functions parse_frame and main.
Fallible operations return Result, forcing the caller to handle both arms explicitly. A match spells out every case; omit one and the code does not compile.
Points of care
- Standard-library end to end — copy it in and it runs.
- Errors travel through
Result; if you drop the?operators while adapting, each call site needs its ownmatch.
Using it
Entry signature: fn parse_frame(data: &[u8], offset: usize) -> Result<u32, CorruptOffset>
Every run emits labeled lines — parsed:, recovered struct: index=, recovered string: — when the file runs.
Execute the file and main walks through parse_frame, in that order.
The key statements that remain
Ok(u32::from_be_bytes(data[offset..offset + 4].try_into().unwrap()))
}
if let Some(err) = payload.downcast_ref::<CorruptOffset>() {
println!("recovered struct: index={} expected={}", err.index, err.expected);
} else if let Some(msg) = payload.downcast_ref::<&str>() {
println!("recovered string: {msg}");
} else {
println!("unknown payload type");
}
Interactive Tools for This Topic
FAQ
- How does the code signal failure?
- No panics — `Result` values carry the failure.
- What does panic any Re-raises Custom Payloads print when run?
- Running the file directly is enough — expect labeled output lines such as `parsed:`, `recovered struct: index=`, `recovered string:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.