Skip to main content

sentry_panic/
lib.rs

1//! The Sentry Panic handler integration.
2//!
3//! The `PanicIntegration`, which is enabled by default in `sentry`, installs a
4//! panic handler that will automatically dispatch all errors to Sentry that
5//! are caused by a panic.
6//! Additionally, panics are forwarded to the previously registered panic hook.
7//!
8//! # Configuration
9//!
10//! The panic integration can be configured with an additional extractor, which
11//! might optionally create a sentry `Event` out of a `PanicHookInfo`.
12//!
13//! ```
14//! let integration = sentry_panic::PanicIntegration::default().add_extractor(|info| None);
15//! ```
16
17#![doc(html_favicon_url = "https://sentry-brand.storage.googleapis.com/favicon.ico")]
18#![doc(html_logo_url = "https://sentry-brand.storage.googleapis.com/sentry-glyph-black.png")]
19#![deny(unsafe_code)]
20
21use std::panic::{self, PanicHookInfo};
22use std::sync::Once;
23
24use sentry_backtrace::current_stacktrace;
25use sentry_core::protocol::{Event, Exception, Level, Mechanism};
26use sentry_core::{ClientOptions, Integration};
27
28/// A panic handler that sends to Sentry.
29///
30/// This panic handler reports panics to Sentry. It also attempts to prevent
31/// double faults in some cases where it's known to be unsafe to invoke the
32/// Sentry panic handler.
33pub fn panic_handler(info: &PanicHookInfo<'_>) {
34    sentry_core::with_integration(|integration: &PanicIntegration, hub| {
35        hub.capture_event(integration.event_from_panic_info(info));
36        if let Some(client) = hub.client() {
37            client.flush(None);
38        }
39    });
40}
41
42type PanicExtractor = dyn Fn(&PanicHookInfo<'_>) -> Option<Event<'static>> + Send + Sync;
43
44/// The Sentry Panic handler Integration.
45#[derive(Default)]
46pub struct PanicIntegration {
47    extractors: Vec<Box<PanicExtractor>>,
48}
49
50impl std::fmt::Debug for PanicIntegration {
51    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
52        f.debug_struct("PanicIntegration")
53            .field("extractors", &self.extractors.len())
54            .finish()
55    }
56}
57
58static INIT: Once = Once::new();
59
60impl Integration for PanicIntegration {
61    fn name(&self) -> &'static str {
62        "panic"
63    }
64
65    fn setup(&self, _cfg: &mut ClientOptions) {
66        INIT.call_once(|| {
67            let next = panic::take_hook();
68            panic::set_hook(Box::new(move |info| {
69                panic_handler(info);
70                next(info);
71            }));
72        });
73    }
74}
75
76/// Extract the message of a panic.
77pub fn message_from_panic_info<'a>(info: &'a PanicHookInfo<'_>) -> &'a str {
78    match info.payload().downcast_ref::<&'static str>() {
79        Some(s) => s,
80        None => match info.payload().downcast_ref::<String>() {
81            Some(s) => &s[..],
82            None => "Box<Any>",
83        },
84    }
85}
86
87impl PanicIntegration {
88    /// Creates a new Panic Integration.
89    pub fn new() -> Self {
90        Self::default()
91    }
92
93    /// Registers a new extractor.
94    #[must_use]
95    pub fn add_extractor<F>(mut self, f: F) -> Self
96    where
97        F: Fn(&PanicHookInfo<'_>) -> Option<Event<'static>> + Send + Sync + 'static,
98    {
99        self.extractors.push(Box::new(f));
100        self
101    }
102
103    /// Creates an event from the given panic info.
104    ///
105    /// The stacktrace is calculated from the current frame.
106    pub fn event_from_panic_info(&self, info: &PanicHookInfo<'_>) -> Event<'static> {
107        for extractor in &self.extractors {
108            if let Some(event) = extractor(info) {
109                return event;
110            }
111        }
112
113        // TODO: We would ideally want to downcast to `std::error:Error` here
114        // and use `event_from_error`, but that way we won‘t get meaningful
115        // backtraces yet.
116
117        let msg = message_from_panic_info(info);
118        Event {
119            exception: vec![Exception {
120                ty: "panic".into(),
121                mechanism: Some(Mechanism {
122                    ty: "panic".into(),
123                    handled: Some(false),
124                    ..Default::default()
125                }),
126                value: Some(msg.to_string()),
127                stacktrace: current_stacktrace(),
128                ..Default::default()
129            }]
130            .into(),
131            level: Level::Fatal,
132            ..Default::default()
133        }
134    }
135}