Skip to main content

datalogic_rs/error/
serde.rs

1//! Serde + `Display` rendering for [`Error`], plus the `From` impls for
2//! foreign parse errors. Split out so `mod.rs` stays focused on the struct
3//! and its constructors.
4
5use super::Error;
6use super::kind::ErrorKind;
7use serde::ser::{Serialize, SerializeMap, Serializer};
8use std::fmt;
9
10impl fmt::Display for Error {
11    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
12        // Render the kind first, then optionally the operator context.
13        write_kind_message(f, &self.kind)?;
14        if let Some(op) = self.operator() {
15            write!(f, " (in operator: {})", op)?;
16        }
17        Ok(())
18    }
19}
20
21/// Render the `ErrorKind` portion of an error message, without the operator
22/// suffix. Single source of truth for the kind → human-readable mapping; used
23/// by `Display for Error` (which then appends the operator context) and
24/// `Error::serialize` (via `KindDisplay`).
25fn write_kind_message(f: &mut fmt::Formatter<'_>, kind: &ErrorKind) -> fmt::Result {
26    match kind {
27        ErrorKind::InvalidOperator(op) => write!(f, "Invalid operator: {}", op),
28        ErrorKind::InvalidArguments(msg) => write!(f, "Invalid arguments: {}", msg),
29        ErrorKind::VariableNotFound(var) => write!(f, "Variable not found: {}", var),
30        ErrorKind::InvalidContextLevel(level) => write!(f, "Invalid context level: {}", level),
31        ErrorKind::TypeError(msg) => write!(f, "Type error: {}", msg),
32        ErrorKind::ArithmeticError(msg) => write!(f, "Arithmetic error: {}", msg),
33        ErrorKind::Custom(err) => write!(f, "{}", err),
34        ErrorKind::ParseError(msg) => write!(f, "Parse error: {}", msg),
35        ErrorKind::Thrown(val) => {
36            #[cfg(feature = "serde_json")]
37            {
38                let json = crate::serde_bridge::owned_to_serde(val);
39                write!(f, "Thrown: {}", json)
40            }
41            #[cfg(not(feature = "serde_json"))]
42            {
43                write!(f, "Thrown: {:?}", val)
44            }
45        }
46        ErrorKind::FormatError(msg) => write!(f, "Format error: {}", msg),
47        ErrorKind::IndexOutOfBounds { index, length } => write!(
48            f,
49            "Index {} out of bounds for array of length {}",
50            index, length
51        ),
52        ErrorKind::ConfigurationError(msg) => write!(f, "Configuration error: {}", msg),
53        ErrorKind::BudgetExceeded { budget, spent } => write!(
54            f,
55            "Operation budget exceeded: {} operations charged against a budget of {}",
56            spent, budget
57        ),
58    }
59}
60
61impl std::error::Error for Error {
62    /// Returns the wrapped source error, but only for [`ErrorKind::Custom`].
63    ///
64    /// All other [`ErrorKind`] variants carry a flat `Cow<'static, str>`
65    /// payload (or a structured value, in `Thrown` / `IndexOutOfBounds`)
66    /// rather than a typed cause, so they have no `dyn Error` to chain to.
67    /// To attach a typed source, wrap your error via [`Error::wrap`] —
68    /// that produces an `ErrorKind::Custom` whose `source()` returns
69    /// `Some(&original)` and whose `Display` matches the original.
70    ///
71    /// ```rust
72    /// use datalogic_rs::Error;
73    /// use std::error::Error as _;
74    ///
75    /// fn read_config() -> std::io::Result<String> {
76    ///     Err(std::io::Error::other("disk fell off the cliff"))
77    /// }
78    ///
79    /// let err = read_config().map_err(Error::wrap).unwrap_err();
80    /// // The original io::Error survives the wrap and can be walked.
81    /// let source = err.source().unwrap();
82    /// assert!(source.to_string().contains("disk"));
83    /// ```
84    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
85        match &self.kind {
86            ErrorKind::Custom(err) => Some(err.as_ref()),
87            _ => None,
88        }
89    }
90}
91
92#[cfg(feature = "serde_json")]
93#[cfg_attr(docsrs, doc(cfg(feature = "serde_json")))]
94impl From<serde_json::Error> for Error {
95    fn from(err: serde_json::Error) -> Self {
96        Error::parse_error(err.to_string())
97    }
98}
99
100impl From<datavalue::ParseError> for Error {
101    fn from(err: datavalue::ParseError) -> Self {
102        Error::parse_error(err.to_string())
103    }
104}
105
106impl From<ErrorKind> for Error {
107    #[inline]
108    fn from(kind: ErrorKind) -> Self {
109        Error::new(kind)
110    }
111}
112
113impl Serialize for Error {
114    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
115        // Shape:
116        // { "type": <tag>, "message": <Display>, ...kind-extras, "operator"?, "node_ids"? }
117        let mut map = serializer.serialize_map(None)?;
118        map.serialize_entry("type", self.tag())?;
119        // The Display impl appends "(in operator: ...)" when set; for the
120        // `message` field we want the kind portion only, so render kind
121        // without the operator suffix. `KindDisplay`'s Serialize impl streams
122        // the Display straight into the output via `collect_str`, avoiding an
123        // intermediate heap `String`.
124        map.serialize_entry("message", &KindDisplay(&self.kind))?;
125        match &self.kind {
126            ErrorKind::VariableNotFound(name) => map.serialize_entry("variable", name)?,
127            ErrorKind::InvalidContextLevel(level) => map.serialize_entry("level", level)?,
128            ErrorKind::Thrown(value) => map.serialize_entry("thrown", value)?,
129            ErrorKind::IndexOutOfBounds { index, length } => {
130                map.serialize_entry("index", index)?;
131                map.serialize_entry("length", length)?;
132            }
133            ErrorKind::BudgetExceeded { budget, spent } => {
134                map.serialize_entry("budget", budget)?;
135                map.serialize_entry("spent", spent)?;
136            }
137            _ => {}
138        }
139        if let Some(op) = self.operator() {
140            map.serialize_entry("operator", op)?;
141        }
142        let ids = self.node_ids();
143        if !ids.is_empty() {
144            map.serialize_entry("node_ids", ids)?;
145        }
146        map.end()
147    }
148}
149
150/// Render an [`ErrorKind`] without the operator suffix. Used by
151/// [`Error::serialize`] to populate the `message` field.
152pub(crate) struct KindDisplay<'a>(pub(crate) &'a ErrorKind);
153
154impl<'a> fmt::Display for KindDisplay<'a> {
155    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
156        write_kind_message(f, self.0)
157    }
158}
159
160impl Serialize for KindDisplay<'_> {
161    /// Stream the kind message straight into the serializer via `collect_str`
162    /// instead of allocating an intermediate `String` with `to_string()`.
163    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
164        serializer.collect_str(self)
165    }
166}