From 0a2ef958c0dca21d19e4ffc38ba5a7c4078e182a Mon Sep 17 00:00:00 2001 From: Weicao-CatilGrass <1992414357@qq.com> Date: Sat, 23 May 2026 23:41:04 +0800 Subject: Rework examples and add entry macro for testing --- examples/example-panic-unwind/src/main.rs | 56 +++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 examples/example-panic-unwind/src/main.rs (limited to 'examples/example-panic-unwind/src/main.rs') diff --git a/examples/example-panic-unwind/src/main.rs b/examples/example-panic-unwind/src/main.rs new file mode 100644 index 0000000..18cf4d6 --- /dev/null +++ b/examples/example-panic-unwind/src/main.rs @@ -0,0 +1,56 @@ +//! Example Panic Unwind +//! +//! > This example introduces how to catch Panic in the Mingling program loop +//! +//! Run: +//! ```bash +//! cargo run --manifest-path examples/example-panic-unwind/Cargo.toml --quiet -- panic +//! cargo run --manifest-path examples/example-panic-unwind/Cargo.toml --quiet -- panic OhMyGod +//! ``` +//! +//! Output: +//! ```plaintext +//! Program not panic +//! Program panic: OhMyGod +//! OhMyGod +//! ``` + +use mingling::{hook::ProgramHook, prelude::*}; + +dispatcher!("panic", CMDPanic => EntryPanic); +pack!(NotPanic = ()); + +fn main() { + let mut program = ThisProgram::new(); + program.with_dispatcher(CMDPanic); + + // --------- IMPORTANT --------- + // Enable silence_panic to suppress automatic Panic output + program.stdout_setting.silence_panic = true; + + // Define a hook to output &ProgramPanic when a Panic occurs + program + .with_hook(ProgramHook::empty().on_exec_panic(|info| println!("Program panic: {}", info))); + // --------- IMPORTANT --------- + + program.exec(); +} + +#[chain] +fn handle_panic(prev: EntryPanic) -> Next { + let panic_info = prev.pick::>(()).unpack(); + match panic_info { + Some(s) => { + // Panic happens here, will be caught + panic!("{}", s) + } + None => NotPanic::default(), + } +} + +#[renderer] +fn render(_: NotPanic) { + r_println!("Program not panic"); +} + +gen_program!(); -- cgit