Skip to main content

prometheus_http_query/
error.rs

1//! All error types that are returned by methods in this crate.
2use serde::Deserialize;
3use std::error::Error as StdError;
4use std::{fmt, num::ParseIntError};
5
6/// A global error enum that contains all errors that are returned by this
7/// library. Some errors are wrappers for errors from underlying libraries.
8/// All errors (this enum as well as all contained structs) implement [`std::error::Error`].
9#[non_exhaustive]
10#[derive(Debug)]
11pub enum Error {
12    /// Wraps errors from the underlying [`reqwest::Client`] that cannot be mapped
13    /// to a more specific error type. Deserialization errors also fall into this
14    /// category.
15    Client(ClientError),
16    /// Occurs when Prometheus responds with e.g. HTTP 4xx (e.g. due to a syntax error in a PromQL query).<br>
17    /// Details on the error as reported by Prometheus are included in [`PrometheusError`].
18    Prometheus(PrometheusError),
19    /// Occurs when the [`Client::series`](crate::Client::series) method is called with an empty set of
20    /// series [`Selector`](crate::selector::Selector)s. According to the Prometheus API description at least one
21    /// [`Selector`](crate::selector::Selector) must be provided.
22    EmptySeriesSelector,
23    /// Wraps errors from the [`url`] crate.
24    ParseUrl(ParseUrlError),
25    /// Wraps errors from parsing integers from strings.
26    ParseInt(ParseIntError),
27    /// Wraps parsing errors that are raised directly from the crate.
28    Parse(String),
29}
30
31impl fmt::Display for Error {
32    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
33        match self {
34            Self::Client(e) => e.fmt(f),
35            Self::Prometheus(e) => e.fmt(f),
36            Self::EmptySeriesSelector => f.write_str("at least one series selector must be provided in order to query the series endpoint"),
37            Self::ParseUrl(e) => e.fmt(f),
38            Self::ParseInt(e) => e.fmt(f),
39            Self::Parse(s) => f.write_str(s)
40        }
41    }
42}
43
44impl StdError for Error {
45    fn source(&self) -> Option<&(dyn StdError + 'static)> {
46        match self {
47            Self::Client(e) => e.source(),
48            Self::Prometheus(_) => None,
49            Self::EmptySeriesSelector => None,
50            Self::ParseUrl(e) => e.source(),
51            Self::ParseInt(e) => e.source(),
52            Self::Parse(_) => None,
53        }
54    }
55}
56
57/// This error is thrown when the JSON response's `status` field contains `error`.<br>
58/// The error-related information from the JSON body is included in this error.
59#[derive(Debug, Clone, PartialEq, Deserialize)]
60pub struct PrometheusError {
61    #[serde(alias = "errorType")]
62    pub(crate) error_type: PrometheusErrorType,
63    #[serde(alias = "error")]
64    pub(crate) message: String,
65}
66
67impl StdError for PrometheusError {}
68
69impl fmt::Display for PrometheusError {
70    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
71        write!(f, "{}: {}", self.error_type, self.message)
72    }
73}
74
75impl PrometheusError {
76    /// Returns the parsed version of the error type that was given by the Prometheus API.
77    pub fn error_type(&self) -> PrometheusErrorType {
78        self.error_type
79    }
80
81    /// Returns the error message that was given by the Prometheus API.
82    pub fn message(&self) -> &str {
83        &self.message
84    }
85
86    pub fn is_timeout(&self) -> bool {
87        self.error_type == PrometheusErrorType::Timeout
88    }
89
90    pub fn is_canceled(&self) -> bool {
91        self.error_type == PrometheusErrorType::Canceled
92    }
93
94    pub fn is_execution(&self) -> bool {
95        self.error_type == PrometheusErrorType::Execution
96    }
97
98    pub fn is_bad_data(&self) -> bool {
99        self.error_type == PrometheusErrorType::BadData
100    }
101
102    pub fn is_internal(&self) -> bool {
103        self.error_type == PrometheusErrorType::Internal
104    }
105
106    pub fn is_unavailable(&self) -> bool {
107        self.error_type == PrometheusErrorType::Unavailable
108    }
109
110    pub fn is_not_found(&self) -> bool {
111        self.error_type == PrometheusErrorType::NotFound
112    }
113}
114
115/// The parsed error type as returned by the Prometheus API.
116#[non_exhaustive]
117#[derive(Clone, Copy, Debug, Deserialize, PartialEq)]
118pub enum PrometheusErrorType {
119    #[serde(alias = "timeout")]
120    Timeout,
121    #[serde(alias = "canceled")]
122    Canceled,
123    #[serde(alias = "execution")]
124    Execution,
125    #[serde(alias = "bad_data")]
126    BadData,
127    #[serde(alias = "internal")]
128    Internal,
129    #[serde(alias = "unavailable")]
130    Unavailable,
131    #[serde(alias = "not_found")]
132    NotFound,
133}
134
135impl fmt::Display for PrometheusErrorType {
136    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
137        match self {
138            Self::Timeout => f.write_str("timeout"),
139            Self::Canceled => f.write_str("canceled"),
140            Self::Execution => f.write_str("execution"),
141            Self::BadData => f.write_str("bad_data"),
142            Self::Internal => f.write_str("internal"),
143            Self::Unavailable => f.write_str("unavailable"),
144            Self::NotFound => f.write_str("not_found"),
145        }
146    }
147}
148
149/// Is thrown when the [`Client`](crate::Client) or the underlying
150/// [`reqwest::Error`] fail to build or execute a request.
151#[derive(Debug)]
152pub struct ClientError {
153    pub(crate) message: &'static str,
154    pub(crate) source: Option<reqwest::Error>,
155}
156
157impl fmt::Display for ClientError {
158    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
159        f.write_str(&self.message)
160    }
161}
162
163impl StdError for ClientError {
164    fn source(&self) -> Option<&(dyn StdError + 'static)> {
165        self.source.as_ref().map(|e| e as &dyn StdError)
166    }
167}
168
169impl ClientError {
170    /// Obtain the [`reqwest::Error`] that is the actual cause of this
171    /// error or `None` if the error originated in [`Client`](crate::Client)
172    /// itself.<br>
173    pub fn inner(&self) -> Option<&reqwest::Error> {
174        self.source.as_ref()
175    }
176}
177
178/// Is thrown when the URL that is used to instantiate the [`Client`](crate::Client)
179/// is invalid.
180#[derive(Debug)]
181pub struct ParseUrlError {
182    pub(crate) message: &'static str,
183    pub(crate) source: url::ParseError,
184}
185
186impl fmt::Display for ParseUrlError {
187    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
188        f.write_str(&self.message)
189    }
190}
191
192impl StdError for ParseUrlError {
193    fn source(&self) -> Option<&(dyn StdError + 'static)> {
194        Some(&self.source)
195    }
196}
197
198impl ParseUrlError {
199    /// Obtain the [`url::ParseError`] that is the actual cause of this error.
200    pub fn inner(&self) -> &url::ParseError {
201        &self.source
202    }
203}