Skip to main content

gcloud_observability/
errors.rs

1use gcloud_sdk::error::Error;
2use opentelemetry_sdk::ExportError;
3use rsb_derive::*;
4
5pub type BoxedError = Box<dyn std::error::Error + Send + Sync>;
6
7pub type GcloudObservabilityResult<E> = Result<E, GcloudObservabilityError>;
8
9#[derive(Debug)]
10pub enum GcloudObservabilityError {
11    SystemError(GcloudObservabilitySystemError),
12    NetworkError(GcloudObservabilityNetworkError),
13    /// A value refused before it was used, such as a malformed project ID.
14    InvalidParametersError(GcloudObservabilityInvalidParametersError),
15}
16
17impl GcloudObservabilityError {
18    pub(crate) fn system(message: impl Into<String>) -> Self {
19        Self::SystemError(GcloudObservabilitySystemError::new(message.into()))
20    }
21
22    pub(crate) fn system_caused_by(
23        message: impl Into<String>,
24        root_cause: impl std::error::Error + Send + Sync + 'static,
25    ) -> Self {
26        Self::SystemError(
27            GcloudObservabilitySystemError::new(message.into())
28                .with_root_cause(Box::new(root_cause)),
29        )
30    }
31
32    pub(crate) fn invalid_parameters(field: impl Into<String>, error: impl Into<String>) -> Self {
33        Self::InvalidParametersError(GcloudObservabilityInvalidParametersError::new(
34            field.into(),
35            error.into(),
36        ))
37    }
38}
39
40impl std::fmt::Display for GcloudObservabilityError {
41    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
42        match *self {
43            GcloudObservabilityError::SystemError(ref err) => err.fmt(f),
44            GcloudObservabilityError::NetworkError(ref err) => err.fmt(f),
45            GcloudObservabilityError::InvalidParametersError(ref err) => err.fmt(f),
46        }
47    }
48}
49
50impl std::error::Error for GcloudObservabilityError {
51    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
52        match *self {
53            GcloudObservabilityError::SystemError(ref err) => err.source(),
54            GcloudObservabilityError::NetworkError(ref err) => err.source(),
55            GcloudObservabilityError::InvalidParametersError(ref err) => err.source(),
56        }
57    }
58}
59
60#[derive(Debug, Builder)]
61pub struct GcloudObservabilitySystemError {
62    pub message: String,
63    pub root_cause: Option<BoxedError>,
64}
65
66impl std::fmt::Display for GcloudObservabilitySystemError {
67    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
68        write!(f, "System error: {:?}", self.message)
69    }
70}
71
72impl std::error::Error for GcloudObservabilitySystemError {
73    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
74        self.root_cause
75            .as_ref()
76            .map(|cause| &**cause as &(dyn std::error::Error + 'static))
77    }
78}
79
80#[derive(Debug, Eq, PartialEq, Clone, Builder)]
81pub struct GcloudObservabilityNetworkError {
82    pub message: String,
83}
84
85impl std::fmt::Display for GcloudObservabilityNetworkError {
86    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
87        write!(f, "Network error: {}", self.message)
88    }
89}
90
91impl std::error::Error for GcloudObservabilityNetworkError {}
92
93#[derive(Debug, Eq, PartialEq, Clone, Builder)]
94pub struct GcloudObservabilityInvalidParametersError {
95    /// The parameter, named as the builders name it: `google_project_id`, `log_id` or
96    /// `endpoint`.
97    pub field: String,
98    /// Why it was refused.
99    pub error: String,
100}
101
102impl std::fmt::Display for GcloudObservabilityInvalidParametersError {
103    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
104        write!(f, "Invalid parameters error: {} {}", self.field, self.error)
105    }
106}
107
108impl std::error::Error for GcloudObservabilityInvalidParametersError {}
109
110impl From<gcloud_sdk::error::Error> for GcloudObservabilityError {
111    fn from(gcloud_error: Error) -> Self {
112        GcloudObservabilityError::system_caused_by("Google SDK error", gcloud_error)
113    }
114}
115
116impl From<gcloud_sdk::tonic::Status> for GcloudObservabilityError {
117    fn from(status: gcloud_sdk::tonic::Status) -> Self {
118        GcloudObservabilityError::NetworkError(GcloudObservabilityNetworkError::new(format!(
119            "{status}"
120        )))
121    }
122}
123
124#[cfg(feature = "otlp")]
125impl From<opentelemetry_otlp::ExporterBuildError> for GcloudObservabilityError {
126    fn from(error: opentelemetry_otlp::ExporterBuildError) -> Self {
127        GcloudObservabilityError::system_caused_by("OTLP exporter error", error)
128    }
129}
130
131impl ExportError for GcloudObservabilityError {
132    fn exporter_name(&self) -> &'static str {
133        "GoogleCloudTraceExporter"
134    }
135}
136
137#[cfg(test)]
138mod tests {
139    use super::*;
140    use gcloud_sdk::error::ErrorKind;
141    use std::error::Error as _;
142
143    #[test]
144    fn source_of_a_system_error_is_its_root_cause() {
145        let error = GcloudObservabilityError::from(Error::from(ErrorKind::CryptoProviderMissing));
146
147        let source = error.source().expect("the root cause is the source");
148
149        assert!(source.is::<Error>());
150        assert!(source.source().is_none());
151    }
152
153    #[test]
154    fn network_error_has_no_source() {
155        let error = GcloudObservabilityError::from(gcloud_sdk::tonic::Status::unavailable("down"));
156
157        assert!(error.source().is_none());
158    }
159
160    #[test]
161    fn system_error_without_a_root_cause_has_no_source() {
162        let error = GcloudObservabilityError::SystemError(GcloudObservabilitySystemError::new(
163            "no project".to_string(),
164        ));
165
166        assert!(error.source().is_none());
167    }
168}