ckb_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 `PanicInfo`.
12//!
13//! ```
14//! use ckb_sentry_panic as sentry_panic;
15//!
16//! let integration = sentry_panic::PanicIntegration::default().add_extractor(|info| None);
17//! ```
18
19#![doc(html_favicon_url = "https://sentry-brand.storage.googleapis.com/favicon.ico")]
20#![doc(html_logo_url = "https://sentry-brand.storage.googleapis.com/sentry-glyph-black.png")]
21#![warn(missing_docs)]
22#![deny(unsafe_code)]
23#![warn(missing_doc_code_examples)]
24
25use std::panic::{self, PanicInfo};
26use std::sync::Once;
27
28use sentry_backtrace::current_stacktrace;
29use sentry_core::protocol::{Event, Exception, Level, Mechanism};
30use sentry_core::{ClientOptions, Integration};
31
32/// A panic handler that sends to Sentry.
33///
34/// This panic handler reports panics to Sentry. It also attempts to prevent
35/// double faults in some cases where it's known to be unsafe to invoke the
36/// Sentry panic handler.
37pub fn panic_handler(info: &PanicInfo<'_>) {
38    sentry_core::with_integration(|integration: &PanicIntegration, hub| {
39        hub.capture_event(integration.event_from_panic_info(info))
40    });
41}
42
43type PanicExtractor = dyn Fn(&PanicInfo<'_>) -> Option<Event<'static>> + Send + Sync;
44
45/// The Sentry Panic handler Integration.
46#[derive(Default)]
47pub struct PanicIntegration {
48    extractors: Vec<Box<PanicExtractor>>,
49}
50
51impl std::fmt::Debug for PanicIntegration {
52    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
53        f.debug_struct("PanicIntegration")
54            .field("extractors", &self.extractors.len())
55            .finish()
56    }
57}
58
59static INIT: Once = Once::new();
60
61impl Integration for PanicIntegration {
62    fn name(&self) -> &'static str {
63        "panic"
64    }
65
66    fn setup(&self, _cfg: &mut ClientOptions) {
67        INIT.call_once(|| {
68            let next = panic::take_hook();
69            panic::set_hook(Box::new(move |info| {
70                panic_handler(info);
71                next(info);
72            }));
73        });
74    }
75}
76
77/// Extract the message of a panic.
78pub fn message_from_panic_info<'a>(info: &'a PanicInfo<'_>) -> &'a str {
79    match info.payload().downcast_ref::<&'static str>() {
80        Some(s) => *s,
81        None => match info.payload().downcast_ref::<String>() {
82            Some(s) => &s[..],
83            None => "Box<Any>",
84        },
85    }
86}
87
88impl PanicIntegration {
89    /// Creates a new Panic Integration.
90    pub fn new() -> Self {
91        Self::default()
92    }
93
94    /// Registers a new extractor.
95    pub fn add_extractor<F>(mut self, f: F) -> Self
96    where
97        F: Fn(&PanicInfo<'_>) -> 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: &PanicInfo<'_>) -> 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}