#![doc(html_favicon_url = "https://sentry-brand.storage.googleapis.com/favicon.ico")]
#![doc(html_logo_url = "https://sentry-brand.storage.googleapis.com/sentry-glyph-black.png")]
#![warn(missing_docs)]
#![deny(unsafe_code)]
use sentry_core::protocol::Event;
use sentry_core::types::Uuid;
use sentry_core::Hub;
pub fn capture_anyhow(e: &anyhow::Error) -> Uuid {
Hub::with_active(|hub| hub.capture_anyhow(e))
}
pub fn event_from_error(err: &anyhow::Error) -> Event<'static> {
let dyn_err: &dyn std::error::Error = err.as_ref();
#[allow(unused_mut)]
let mut event = sentry_core::event_from_error(dyn_err);
#[cfg(feature = "backtrace")]
{
if let Some(exc) = event.exception.iter_mut().last() {
let backtrace = err.backtrace();
if matches!(
backtrace.status(),
std::backtrace::BacktraceStatus::Captured
) {
exc.stacktrace = sentry_backtrace::parse_stacktrace(&format!("{backtrace:#}"));
}
}
}
event
}
pub trait AnyhowHubExt {
fn capture_anyhow(&self, e: &anyhow::Error) -> Uuid;
}
impl AnyhowHubExt for Hub {
fn capture_anyhow(&self, anyhow_error: &anyhow::Error) -> Uuid {
let event = event_from_error(anyhow_error);
self.capture_event(event)
}
}
#[cfg(all(feature = "backtrace", test))]
mod tests {
use super::*;
#[test]
fn test_event_from_error_with_backtrace() {
std::env::set_var("RUST_BACKTRACE", "1");
let event = event_from_error(&anyhow::anyhow!("Oh jeez"));
let stacktrace = event.exception[0].stacktrace.as_ref().unwrap();
let found_test_fn = stacktrace
.frames
.iter()
.find(|frame| match &frame.function {
Some(f) => f.contains("test_event_from_error_with_backtrace"),
None => false,
});
assert!(found_test_fn.is_some());
}
#[test]
fn test_capture_anyhow_uses_event_from_error_helper() {
std::env::set_var("RUST_BACKTRACE", "1");
let err = &anyhow::anyhow!("Oh jeez");
let event = event_from_error(err);
let events = sentry::test::with_captured_events(|| {
capture_anyhow(err);
});
assert_eq!(event.exception, events[0].exception);
}
}