1#![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
32pub 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#[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
77pub 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 pub fn new() -> Self {
91 Self::default()
92 }
93
94 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 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 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}