opentelemetry/global/
error_handler.rs

1use std::sync::PoisonError;
2use std::sync::RwLock;
3
4#[cfg(feature = "logs")]
5use crate::logs::LogError;
6#[cfg(feature = "metrics")]
7use crate::metrics::MetricsError;
8use crate::propagation::PropagationError;
9#[cfg(feature = "trace")]
10use crate::trace::TraceError;
11use once_cell::sync::Lazy;
12
13static GLOBAL_ERROR_HANDLER: Lazy<RwLock<Option<ErrorHandler>>> = Lazy::new(|| RwLock::new(None));
14
15/// Wrapper for error from both tracing and metrics part of open telemetry.
16#[derive(thiserror::Error, Debug)]
17#[non_exhaustive]
18pub enum Error {
19    #[cfg(feature = "trace")]
20    #[cfg_attr(docsrs, doc(cfg(feature = "trace")))]
21    #[error(transparent)]
22    /// Failed to export traces.
23    Trace(#[from] TraceError),
24    #[cfg(feature = "metrics")]
25    #[cfg_attr(docsrs, doc(cfg(feature = "metrics")))]
26    #[error(transparent)]
27    /// An issue raised by the metrics module.
28    Metric(#[from] MetricsError),
29
30    #[cfg(feature = "logs")]
31    #[cfg_attr(docsrs, doc(cfg(feature = "logs")))]
32    #[error(transparent)]
33    /// Failed to export logs.
34    Log(#[from] LogError),
35
36    #[error(transparent)]
37    /// Error happens when injecting and extracting information using propagators.
38    Propagation(#[from] PropagationError),
39
40    #[error("{0}")]
41    /// Other types of failures not covered by the variants above.
42    Other(String),
43}
44
45impl<T> From<PoisonError<T>> for Error {
46    fn from(err: PoisonError<T>) -> Self {
47        Error::Other(err.to_string())
48    }
49}
50
51struct ErrorHandler(Box<dyn Fn(Error) + Send + Sync>);
52
53/// Handle error using the globally configured error handler.
54///
55/// Writes to stderr if unset.
56pub fn handle_error<T: Into<Error>>(err: T) {
57    match GLOBAL_ERROR_HANDLER.read() {
58        Ok(handler) if handler.is_some() => (handler.as_ref().unwrap().0)(err.into()),
59        _ => match err.into() {
60            #[cfg(feature = "metrics")]
61            #[cfg_attr(docsrs, doc(cfg(feature = "metrics")))]
62            Error::Metric(err) => eprintln!("OpenTelemetry metrics error occurred. {}", err),
63            #[cfg(feature = "trace")]
64            #[cfg_attr(docsrs, doc(cfg(feature = "trace")))]
65            Error::Trace(err) => eprintln!("OpenTelemetry trace error occurred. {}", err),
66            #[cfg(feature = "logs")]
67            #[cfg_attr(docsrs, doc(cfg(feature = "logs")))]
68            Error::Log(err) => eprintln!("OpenTelemetry log error occurred. {}", err),
69            Error::Propagation(err) => {
70                eprintln!("OpenTelemetry propagation error occurred. {}", err)
71            }
72            Error::Other(err_msg) => eprintln!("OpenTelemetry error occurred. {}", err_msg),
73        },
74    }
75}
76
77/// Set global error handler.
78pub fn set_error_handler<F>(f: F) -> std::result::Result<(), Error>
79where
80    F: Fn(Error) + Send + Sync + 'static,
81{
82    GLOBAL_ERROR_HANDLER
83        .write()
84        .map(|mut handler| *handler = Some(ErrorHandler(Box::new(f))))
85        .map_err(Into::into)
86}