diff --git a/pgrx-pg-sys/src/submodules/panic.rs b/pgrx-pg-sys/src/submodules/panic.rs index 0a621bd61c..c05e63f2d8 100644 --- a/pgrx-pg-sys/src/submodules/panic.rs +++ b/pgrx-pg-sys/src/submodules/panic.rs @@ -304,14 +304,23 @@ fn take_panic_location() -> ErrorReportLocation { } pub fn register_pg_guard_panic_hook() { - std::panic::set_hook(Box::new(|info| { - PANIC_LOCATION.with(|thread_local| { - thread_local.replace({ - let mut info: ErrorReportLocation = info.into(); - info.backtrace = Some(std::backtrace::Backtrace::capture()); - Some(info) - }) - }); + use super::thread_check::is_os_main_thread; + + let default_hook = std::panic::take_hook(); + std::panic::set_hook(Box::new(move |info: _| { + if is_os_main_thread() == Some(true) { + // if this is the main thread, swallow the panic message and use postgres' error-reporting mechanism. + PANIC_LOCATION.with(|thread_local| { + thread_local.replace({ + let mut info: ErrorReportLocation = info.into(); + info.backtrace = Some(std::backtrace::Backtrace::capture()); + Some(info) + }) + }); + } else { + // if this isn't the main thread, we don't know which connection to associate the panic with. + default_hook(info) + } })) } diff --git a/pgrx-pg-sys/src/submodules/thread_check.rs b/pgrx-pg-sys/src/submodules/thread_check.rs index cf3a1673d6..19d02c0437 100644 --- a/pgrx-pg-sys/src/submodules/thread_check.rs +++ b/pgrx-pg-sys/src/submodules/thread_check.rs @@ -47,7 +47,7 @@ pub(crate) fn check_active_thread() { /// Concretely, it is very important that this not return `Some(false)` /// incorrectly, but the other values are less important. Callers generally /// should compare the result against `Some(false)`. -fn is_os_main_thread() -> Option { +pub(super) fn is_os_main_thread() -> Option { #[cfg(any(target_os = "macos", target_os = "openbsd", target_os = "freebsd"))] return unsafe { match libc::pthread_main_np() { @@ -116,7 +116,7 @@ fn thread_id_check_failed() -> ! { // I don't think this can ever happen, but it would be a bug if it could. assert_ne!(is_os_main_thread(), Some(true), "`pgrx` active thread is not the main thread!?"); panic!( - "{}: postgres FFI may not not be called from multiple threads.", + "{}: postgres FFI may not be called from multiple threads.", std::panic::Location::caller() ); }