1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
use std::sync::PoisonError;
use std::sync::RwLock;
#[cfg(feature = "metrics")]
use crate::metrics::MetricsError;
#[cfg(feature = "trace")]
use crate::trace::TraceError;
lazy_static::lazy_static! {
static ref GLOBAL_ERROR_HANDLER: RwLock<Option<ErrorHandler>> = RwLock::new(None);
}
#[derive(thiserror::Error, Debug)]
#[non_exhaustive]
pub enum Error {
#[cfg(feature = "trace")]
#[cfg_attr(docsrs, doc(cfg(feature = "trace")))]
#[error(transparent)]
Trace(#[from] TraceError),
#[cfg(feature = "metrics")]
#[cfg_attr(docsrs, doc(cfg(feature = "metrics")))]
#[error(transparent)]
Metric(#[from] MetricsError),
#[error("{0}")]
Other(String),
}
impl<T> From<PoisonError<T>> for Error {
fn from(err: PoisonError<T>) -> Self {
Error::Other(err.to_string())
}
}
struct ErrorHandler(Box<dyn Fn(Error) + Send + Sync>);
pub fn handle_error<T: Into<Error>>(err: T) {
match GLOBAL_ERROR_HANDLER.read() {
Ok(handler) if handler.is_some() => (handler.as_ref().unwrap().0)(err.into()),
_ => match err.into() {
#[cfg(feature = "metrics")]
#[cfg_attr(docsrs, doc(cfg(feature = "metrics")))]
Error::Metric(err) => eprintln!("OpenTelemetry metrics error occurred. {}", err),
#[cfg(feature = "trace")]
#[cfg_attr(docsrs, doc(cfg(feature = "trace")))]
Error::Trace(err) => eprintln!("OpenTelemetry trace error occurred. {}", err),
Error::Other(err_msg) => eprintln!("OpenTelemetry error occurred. {}", err_msg),
},
}
}
pub fn set_error_handler<F>(f: F) -> std::result::Result<(), Error>
where
F: Fn(Error) + Send + Sync + 'static,
{
GLOBAL_ERROR_HANDLER
.write()
.map(|mut handler| *handler = Some(ErrorHandler(Box::new(f))))
.map_err(Into::into)
}