Skip to main content

sentry_anyhow/
lib.rs

1//! Adds support for capturing Sentry errors from [`anyhow::Error`].
2//!
3//! This integration adds a new event *source*, which allows you to create events directly
4//! from an [`anyhow::Error`] struct.  As it is only an event source it only needs to be
5//! enabled using the `anyhow` cargo feature, it does not need to be enabled in the call to
6//! [`sentry::init`](https://docs.rs/sentry/*/sentry/fn.init.html).
7//!
8//! This integration does not need to be installed, instead it provides an extra function to
9//! capture [`anyhow::Error`], optionally exposing it as a method on the
10//! [`sentry::Hub`](https://docs.rs/sentry/*/sentry/struct.Hub.html) using the
11//! [`AnyhowHubExt`] trait.
12//!
13//! Like a plain [`std::error::Error`] being captured, [`anyhow::Error`] is captured with a
14//! chain of all error sources, if present.  See
15//! [`sentry::capture_error`](https://docs.rs/sentry/*/sentry/fn.capture_error.html) for
16//! details of this.
17//!
18//! # Example
19//!
20//! ```no_run
21//! use sentry_anyhow::capture_anyhow;
22//!
23//! fn function_that_might_fail() -> anyhow::Result<()> {
24//!     Err(anyhow::anyhow!("some kind of error"))
25//! }
26//!
27//! if let Err(err) = function_that_might_fail() {
28//!     capture_anyhow(&err);
29//! }
30//! ```
31//!
32//! # Features
33//!
34//! The `backtrace` feature will enable the corresponding feature in anyhow and allow you to
35//! capture backtraces with your events.  It is enabled by default.
36//!
37//! [`anyhow::Error`]: https://docs.rs/anyhow/*/anyhow/struct.Error.html
38
39#![doc(html_favicon_url = "https://sentry-brand.storage.googleapis.com/favicon.ico")]
40#![doc(html_logo_url = "https://sentry-brand.storage.googleapis.com/sentry-glyph-black.png")]
41#![deny(unsafe_code)]
42
43use sentry_core::protocol::Event;
44use sentry_core::types::Uuid;
45use sentry_core::Hub;
46
47/// Captures an [`anyhow::Error`].
48///
49/// This will capture an anyhow error as a sentry event if a
50/// [`sentry::Client`](../../struct.Client.html) is initialised, otherwise it will be a
51/// no-op.  The event is dispatched to the thread-local hub, with semantics as described in
52/// [`Hub::current`].
53///
54/// See [module level documentation](index.html) for more information.
55///
56/// [`anyhow::Error`]: https://docs.rs/anyhow/*/anyhow/struct.Error.html
57pub fn capture_anyhow(e: &anyhow::Error) -> Uuid {
58    Hub::with_active(|hub| hub.capture_anyhow(e))
59}
60
61/// Helper function to create an event from a `anyhow::Error`.
62pub fn event_from_error(err: &anyhow::Error) -> Event<'static> {
63    let dyn_err: &dyn std::error::Error = err.as_ref();
64
65    let event = sentry_core::event_from_error(dyn_err);
66
67    #[cfg(feature = "backtrace")]
68    let event = {
69        let mut event = event;
70        // exception records are sorted in reverse
71        if let Some(exc) = event.exception.iter_mut().last() {
72            let backtrace = err.backtrace();
73            if matches!(
74                backtrace.status(),
75                std::backtrace::BacktraceStatus::Captured
76            ) {
77                exc.stacktrace = sentry_backtrace::parse_stacktrace(&format!("{backtrace:#}"));
78            }
79        }
80        event
81    };
82
83    event
84}
85
86/// Hub extension methods for working with [`anyhow`].
87pub trait AnyhowHubExt {
88    /// Captures an [`anyhow::Error`] on a specific hub.
89    fn capture_anyhow(&self, e: &anyhow::Error) -> Uuid;
90}
91
92impl AnyhowHubExt for Hub {
93    fn capture_anyhow(&self, anyhow_error: &anyhow::Error) -> Uuid {
94        let event = event_from_error(anyhow_error);
95        self.capture_event(event)
96    }
97}
98
99#[cfg(all(feature = "backtrace", test))]
100mod tests {
101    use super::*;
102
103    #[test]
104    fn test_event_from_error_with_backtrace() {
105        std::env::set_var("RUST_BACKTRACE", "1");
106
107        let event = event_from_error(&anyhow::anyhow!("Oh jeez"));
108
109        let stacktrace = event.exception[0].stacktrace.as_ref().unwrap();
110        let found_test_fn = stacktrace
111            .frames
112            .iter()
113            .find(|frame| match &frame.function {
114                Some(f) => f.contains("test_event_from_error_with_backtrace"),
115                None => false,
116            });
117
118        assert!(found_test_fn.is_some());
119    }
120
121    #[test]
122    fn test_capture_anyhow_uses_event_from_error_helper() {
123        std::env::set_var("RUST_BACKTRACE", "1");
124
125        let err = &anyhow::anyhow!("Oh jeez");
126
127        let event = event_from_error(err);
128        let events = sentry::test::with_captured_events(|| {
129            capture_anyhow(err);
130        });
131
132        assert_eq!(event.exception, events[0].exception);
133    }
134}