Skip to main content

datadog_agent_config/
translate_error.rs

1//! The error types recorded by the configuration translator and surfaced by the witness driver.
2
3use std::fmt;
4
5/// An error produced while translating a witnessed Datadog configuration value into the
6/// ADP-native model. Names the offending Datadog key, and optionally a human-readable note
7/// and/or the underlying error object.
8#[derive(Debug)]
9pub struct TranslateError {
10    key: String,
11    context: Option<String>,
12    error: Option<Box<dyn std::error::Error + Send + Sync + 'static>>,
13}
14
15pub type BoxError = Box<dyn std::error::Error + Send + Sync + 'static>;
16
17impl TranslateError {
18    /// Returns the Datadog key whose value failed to translate.
19    pub fn key(&self) -> &str {
20        &self.key
21    }
22
23    /// Create a translation error wrapping an underlying error.
24    ///
25    /// Produces `error translating config key `{key}`: {error}`.
26    pub fn new<S, E>(key: S, error: E) -> Self
27    where
28        S: Into<String>,
29        E: Into<BoxError>,
30    {
31        Self {
32            key: key.into(),
33            context: None,
34            error: Some(error.into()),
35        }
36    }
37
38    /// Create a translation error wrapping an underlying error and adding a contextual message.
39    ///
40    /// Produces `error translating config key `{key}`, {context}: {error}`.
41    pub fn new_with_context<S1, S2, E>(key: S1, context: S2, error: E) -> Self
42    where
43        S1: Into<String>,
44        S2: Into<String>,
45        E: Into<BoxError>,
46    {
47        Self {
48            key: key.into(),
49            context: Some(context.into()),
50            error: Some(error.into()),
51        }
52    }
53
54    /// Create a translation error when no underlying error object exists.
55    ///
56    /// Produces `error translating config key `{key}`, {message}`.
57    pub fn new_with_message<S1, S2>(key: S1, message: S2) -> Self
58    where
59        S1: Into<String>,
60        S2: Into<String>,
61    {
62        Self {
63            key: key.into(),
64            context: Some(message.into()),
65            error: None,
66        }
67    }
68}
69
70impl fmt::Display for TranslateError {
71    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72        write!(f, "error translating config key `{}`", self.key)?;
73        if let Some(context) = &self.context {
74            write!(f, ", {context}")?;
75        }
76        if let Some(error) = &self.error {
77            write!(f, ": {error}")?;
78        }
79        Ok(())
80    }
81}
82
83impl std::error::Error for TranslateError {
84    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
85        self.error.as_deref().map(|s| s as &(dyn std::error::Error + 'static))
86    }
87}
88
89/// Every error [`drive`][crate::drive] recorded, non-empty by construction.
90///
91/// A collection of failures has no single `source`. Only [`drive`][crate::drive] constructs it,
92/// and only when at least one key failed.
93#[derive(Debug)]
94pub struct TranslateErrors(Vec<TranslateError>);
95
96impl TranslateErrors {
97    /// Wraps the recorded errors. Callers must pass a non-empty vec.
98    pub(crate) fn new(errors: Vec<TranslateError>) -> Self {
99        debug_assert!(!errors.is_empty(), "TranslateErrors must be non-empty");
100        Self(errors)
101    }
102}
103
104impl<'a> IntoIterator for &'a TranslateErrors {
105    type Item = &'a TranslateError;
106    type IntoIter = std::slice::Iter<'a, TranslateError>;
107
108    fn into_iter(self) -> Self::IntoIter {
109        self.0.iter()
110    }
111}
112
113impl fmt::Display for TranslateErrors {
114    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
115        write!(f, "{} config translation error(s):", self.0.len())?;
116        for error in &self.0 {
117            write!(f, "\n  - {error}")?;
118        }
119        Ok(())
120    }
121}
122
123impl std::error::Error for TranslateErrors {}