Function preserve_panic_message

Source
pub fn preserve_panic_message<F: FnOnce(&mut EasyCurses) -> R + UnwindSafe, R>(
    user_function: F,
) -> Result<R, Option<String>>
Expand description

Wraps the use of curses with catch_unwind to preserve panic info.

Normally, if your program panics while in curses mode the panic message prints immediately and then is destroyed before you can see it by the automatic cleanup of curses mode. Instead, this runs the function you pass it within catch_unwind and when there’s a panic it catches the panic value and attempts to downcast it into a String you can print out or log or whatever you like. Since a panic value can be anything at all this won’t always succeed, thus the Option wrapper on the Err case. Regardless of what of Result you get back, curses mode will be fully cleaned up and shut down by the time this function returns.

Note that you don’t have to use this if you just want your terminal restored to normal when your program panics while in curses mode. That is handled automatically by the Drop implementation of EasyCurses. You only need to use this if you care about the panic message itself.

Examples found in repository?
examples/preserve_panic_message.rs (lines 8-17)
6fn main() {
7    // We wrap all our use of curses with this function.
8    preserve_panic_message(|easy| {
9        // In here we get an initialized EasyCurses handle and then proceed to
10        // use it exactly like we normally would use it.
11        easy.set_cursor_visibility(CursorVisibility::Invisible);
12        easy.set_echo(false);
13        easy.print("Hello world.");
14        easy.refresh();
15        easy.get_input();
16        panic!("oh no");
17    }).unwrap_or_else(|e| match e {
18        // This block only runs if there was an error. We might or might not
19        // have been able to recover an error message. You technically can pass
20        // any value into a panic, but we only get an error message if the panic
21        // value was a `String` or `&str`.
22        Some(errmsg) => println!("Error Occurred: {}", errmsg),
23        None => println!("There was an error, but no error message."),
24    });
25}