From e046201a3edc22df5c00eaebc29bd978b8efde41 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?L=C3=A9o=20Gaspard?= Date: Sun, 4 Dec 2022 19:03:37 +0100 Subject: [PATCH] Expose a function to stringify a PanicInfo struct This allows users who want to display the error message generated by console_error_panic_hook outside of the console to do it without having to reimplement javascript-based stack walking themselves. --- src/lib.rs | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 89945d5..e99ca12 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -94,7 +94,7 @@ cfg_if! { fn stack(error: &Error) -> String; } - fn hook_impl(info: &panic::PanicInfo) { + fn stringify_impl(info: &panic::PanicInfo) -> String { let mut msg = info.to_string(); // Add the error stack to our message. @@ -117,13 +117,21 @@ cfg_if! { // doing that by appending some whitespace. // https://github.com/rustwasm/console_error_panic_hook/issues/7 msg.push_str("\n\n"); + + msg + } - // Finally, log the panic with `console.error`! - error(msg); + fn hook_impl(info: &panic::PanicInfo) { + // Log the panic with `console.error` + error(stringify_impl(info)); } } else { use std::io::{self, Write}; + fn stringify_impl(info: &panic::PanicInfo) -> String { + format!("{}", info) + } + fn hook_impl(info: &panic::PanicInfo) { let _ = writeln!(io::stderr(), "{}", info); } @@ -150,3 +158,9 @@ pub fn set_once() { panic::set_hook(Box::new(hook)); }); } + +/// Return the string that would be displayed to the console by the `console.error` panic +/// hook if it were set. +pub fn stringify(info: &panic::PanicInfo) -> String { + stringify_impl(info) +}