1use alloc::borrow::Cow;
17use alloc::boxed::Box;
18use core::fmt;
19
20use how_far::{AsStopReason, StopReason};
21use whereat::At;
22
23pub type MetricResult<T> = Result<T, At<MetricError>>;
26
27#[non_exhaustive]
31#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
32pub enum ErrorKind {
33 UnsupportedInput,
36 DimensionMismatch,
39 TooSmall,
41 InvalidInput,
44 Degenerate,
48 InvalidConfig,
51 NoMap,
53 UnsupportedRequest,
56 Stopped(StopReason),
59 Resource,
61 Backend,
63 Internal,
65}
66
67impl ErrorKind {
68 pub const fn as_str(self) -> &'static str {
71 match self {
72 ErrorKind::UnsupportedInput => "unsupported_input",
73 ErrorKind::DimensionMismatch => "dimension_mismatch",
74 ErrorKind::TooSmall => "too_small",
75 ErrorKind::InvalidInput => "invalid_input",
76 ErrorKind::Degenerate => "degenerate",
77 ErrorKind::InvalidConfig => "invalid_config",
78 ErrorKind::NoMap => "no_map",
79 ErrorKind::UnsupportedRequest => "unsupported_request",
80 ErrorKind::Stopped(_) => "stopped",
81 ErrorKind::Resource => "resource",
82 ErrorKind::Backend => "backend",
83 ErrorKind::Internal => "internal",
84 }
85 }
86
87 pub const fn is_deterministic(self) -> bool {
90 !matches!(
91 self,
92 ErrorKind::Stopped(_) | ErrorKind::Resource | ErrorKind::Backend
93 )
94 }
95}
96
97impl fmt::Display for ErrorKind {
98 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
99 match self {
100 ErrorKind::Stopped(r) => write!(f, "stopped: {r}"),
101 other => f.write_str(other.as_str()),
102 }
103 }
104}
105
106#[non_exhaustive]
112pub struct MetricError(Box<Repr>);
113
114struct Repr {
115 kind: ErrorKind,
116 metric: Option<&'static str>,
117 message: Option<Cow<'static, str>>,
118 detail: Option<Box<dyn core::error::Error + Send + Sync>>,
119}
120
121impl MetricError {
122 #[track_caller]
124 pub fn from_located<E>(kind: ErrorKind, detail: At<E>) -> At<Self>
125 where
126 E: core::error::Error + Send + Sync + 'static,
127 {
128 detail.map_error(|e| Self::from_detail(kind, e)).at()
129 }
130
131 pub fn new(kind: ErrorKind) -> Self {
133 MetricError(Box::new(Repr {
134 kind,
135 metric: None,
136 message: None,
137 detail: None,
138 }))
139 }
140
141 pub fn from_detail<E>(kind: ErrorKind, detail: E) -> Self
143 where
144 E: core::error::Error + Send + Sync + 'static,
145 {
146 Self::new(kind).with_detail(detail)
147 }
148
149 pub fn stopped(reason: StopReason) -> Self {
151 Self::new(ErrorKind::Stopped(reason))
152 }
153
154 #[must_use]
156 pub fn with_detail<E>(mut self, detail: E) -> Self
157 where
158 E: core::error::Error + Send + Sync + 'static,
159 {
160 self.0.detail = Some(Box::new(detail));
161 self
162 }
163
164 #[must_use]
166 pub fn with_boxed_detail(mut self, detail: Box<dyn core::error::Error + Send + Sync>) -> Self {
167 self.0.detail = Some(detail);
168 self
169 }
170
171 #[must_use]
173 pub fn with_metric(mut self, family: &'static str) -> Self {
174 self.0.metric = Some(family);
175 self
176 }
177
178 #[must_use]
180 pub fn with_message(mut self, message: impl Into<Cow<'static, str>>) -> Self {
181 self.0.message = Some(message.into());
182 self
183 }
184
185 pub fn kind(&self) -> ErrorKind {
187 self.0.kind
188 }
189
190 pub fn metric(&self) -> Option<&'static str> {
192 self.0.metric
193 }
194
195 pub fn message(&self) -> Option<&str> {
197 self.0.message.as_deref()
198 }
199
200 pub fn detail(&self) -> Option<&(dyn core::error::Error + 'static)> {
202 self.0
203 .detail
204 .as_deref()
205 .map(|d| d as &(dyn core::error::Error + 'static))
206 }
207}
208
209impl fmt::Debug for MetricError {
210 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
211 f.debug_struct("MetricError")
212 .field("kind", &self.0.kind)
213 .field("metric", &self.0.metric)
214 .field("message", &self.0.message)
215 .field("detail", &self.0.detail)
216 .finish()
217 }
218}
219
220impl fmt::Display for MetricError {
221 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
223 if let Some(m) = self.0.metric {
224 write!(f, "{m}: ")?;
225 }
226 write!(f, "{}", self.0.kind)?;
227 if let Some(msg) = &self.0.message {
228 write!(f, ": {msg}")?;
229 }
230 if let Some(d) = &self.0.detail {
231 write!(f, ": {d}")?;
232 }
233 Ok(())
234 }
235}
236
237impl core::error::Error for MetricError {
238 fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
239 self.detail()
240 }
241}
242
243impl From<StopReason> for MetricError {
244 fn from(reason: StopReason) -> Self {
245 MetricError::stopped(reason)
246 }
247}
248
249impl AsStopReason for MetricError {
250 fn as_stop_reason(&self) -> Option<StopReason> {
251 match self.0.kind {
252 ErrorKind::Stopped(r) => Some(r),
253 _ => None,
254 }
255 }
256}
257
258pub fn stop_reason(error: &At<MetricError>) -> Option<StopReason> {
261 error.error().as_stop_reason()
262}
263
264pub fn is_stopped(error: &At<MetricError>) -> bool {
268 stop_reason(error).is_some()
269}
270
271pub fn find_metric_error<'a>(
275 error: &'a (dyn core::error::Error + 'static),
276) -> Option<&'a MetricError> {
277 let mut cur: Option<&'a (dyn core::error::Error + 'static)> = Some(error);
278 while let Some(e) = cur {
279 if let Some(at) = e.downcast_ref::<At<MetricError>>() {
280 return Some(at.error());
281 }
282 if let Some(m) = e.downcast_ref::<MetricError>() {
283 return Some(m);
284 }
285 if let Some(b) = e.downcast_ref::<Box<At<MetricError>>>() {
286 return Some(b.error());
287 }
288 cur = e.source();
289 }
290 None
291}
292
293#[track_caller]
295pub fn fail<T>(error: MetricError) -> MetricResult<T> {
296 Err(whereat::at(error))
297}
298
299pub trait ResultMetricExt<T> {
302 #[track_caller]
305 fn metric_err(self, family: &'static str, kind: ErrorKind) -> MetricResult<T>;
306
307 #[track_caller]
309 fn metric_err_with(
310 self,
311 family: &'static str,
312 classify: impl FnOnce(&Self::Error) -> ErrorKind,
313 ) -> MetricResult<T>
314 where
315 Self: Sized;
316
317 type Error;
319}
320
321impl<T, E> ResultMetricExt<T> for Result<T, E>
322where
323 E: core::error::Error + Send + Sync + 'static,
324{
325 type Error = E;
326
327 #[track_caller]
328 fn metric_err(self, family: &'static str, kind: ErrorKind) -> MetricResult<T> {
329 match self {
330 Ok(v) => Ok(v),
331 Err(e) => Err(whereat::at(
332 MetricError::from_detail(kind, e).with_metric(family),
333 )),
334 }
335 }
336
337 #[track_caller]
338 fn metric_err_with(
339 self,
340 family: &'static str,
341 classify: impl FnOnce(&E) -> ErrorKind,
342 ) -> MetricResult<T> {
343 match self {
344 Ok(v) => Ok(v),
345 Err(e) => {
346 let kind = classify(&e);
347 Err(whereat::at(
348 MetricError::from_detail(kind, e).with_metric(family),
349 ))
350 }
351 }
352 }
353}
354
355#[cfg(test)]
356mod tests {
357 use super::*;
358 use alloc::string::ToString;
359
360 #[derive(Debug)]
361 struct Leaf;
362 impl fmt::Display for Leaf {
363 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
364 f.write_str("leaf failed")
365 }
366 }
367 impl core::error::Error for Leaf {}
368
369 #[test]
370 fn display_kind_detail_and_source() {
371 let e = MetricError::from_detail(ErrorKind::TooSmall, Leaf).with_metric("gmsd");
372 assert_eq!(e.to_string(), "gmsd: too_small: leaf failed");
373 assert!(core::error::Error::source(&e).is_some());
374 assert_eq!(e.kind(), ErrorKind::TooSmall);
375 assert!(e.kind().is_deterministic());
376 }
377
378 #[test]
379 fn stop_reason_round_trips_through_as_stop_reason() {
380 let e: MetricError = StopReason::Cancelled.into();
381 assert_eq!(e.as_stop_reason(), Some(StopReason::Cancelled));
382 assert!(!e.kind().is_deterministic());
383 let located = whereat::at(e);
384 assert_eq!(stop_reason(&located), Some(StopReason::Cancelled));
385 let other = whereat::at(MetricError::new(ErrorKind::NoMap));
386 assert_eq!(stop_reason(&other), None);
387 }
388
389 #[test]
390 fn recoverable_after_erasure() {
391 let r: Result<(), Leaf> = Err(Leaf);
392 let err = r.metric_err("fsim", ErrorKind::InvalidInput).unwrap_err();
393 let boxed: Box<dyn core::error::Error + Send + Sync> = Box::new(err);
394 let found = find_metric_error(&*boxed).expect("envelope recoverable");
395 assert_eq!(found.kind(), ErrorKind::InvalidInput);
396 assert_eq!(found.metric(), Some("fsim"));
397 }
398
399 #[test]
400 fn located_at_the_caller() {
401 let r: Result<(), Leaf> = Err(Leaf);
402 let line = line!() + 1;
403 let err = r.metric_err("fsim", ErrorKind::InvalidInput).unwrap_err();
404 let frame = err.frames().next().expect("one frame");
405 let loc = frame.location().expect("location recorded");
406 assert_eq!(loc.line(), line);
407 assert!(loc.file().ends_with("error.rs"));
408 }
409
410 #[test]
411 fn error_types_are_send_sync() {
412 fn assert_send_sync<T: Send + Sync>() {}
413 assert_send_sync::<MetricError>();
414 assert_send_sync::<At<MetricError>>();
415 }
416}