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    }
54}
55
56impl std::error::Error for Error {
57    /// Returns the wrapped source error, but only for [`ErrorKind::Custom`].
58    ///
59    /// All other [`ErrorKind`] variants carry a flat `Cow<'static, str>`
60    /// payload (or a structured value, in `Thrown` / `IndexOutOfBounds`)
61    /// rather than a typed cause, so they have no `dyn Error` to chain to.
62    /// To attach a typed source, wrap your error via [`Error::wrap`] —
63    /// that produces an `ErrorKind::Custom` whose `source()` returns
64    /// `Some(&original)` and whose `Display` matches the original.
65    ///
66    /// ```rust
67    /// use datalogic_rs::Error;
68    /// use std::error::Error as _;
69    ///
70    /// fn read_config() -> std::io::Result<String> {
71    ///     Err(std::io::Error::other("disk fell off the cliff"))
72    /// }
73    ///
74    /// let err = read_config().map_err(Error::wrap).unwrap_err();
75    /// // The original io::Error survives the wrap and can be walked.
76    /// let source = err.source().unwrap();
77    /// assert!(source.to_string().contains("disk"));
78    /// ```
79    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
80        match &self.kind {
81            ErrorKind::Custom(err) => Some(err.as_ref()),
82            _ => None,
83        }
84    }
85}
86
87#[cfg(feature = "serde_json")]
88#[cfg_attr(docsrs, doc(cfg(feature = "serde_json")))]
89impl From<serde_json::Error> for Error {
90    fn from(err: serde_json::Error) -> Self {
91        Error::parse_error(err.to_string())
92    }
93}
94
95impl From<datavalue::ParseError> for Error {
96    fn from(err: datavalue::ParseError) -> Self {
97        Error::parse_error(err.to_string())
98    }
99}
100
101impl From<ErrorKind> for Error {
102    #[inline]
103    fn from(kind: ErrorKind) -> Self {
104        Error::new(kind)
105    }
106}
107
108impl Serialize for Error {
109    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
110        // Shape:
111        // { "type": <tag>, "message": <Display>, ...kind-extras, "operator"?, "node_ids"? }
112        let mut map = serializer.serialize_map(None)?;
113        map.serialize_entry("type", self.tag())?;
114        // The Display impl appends "(in operator: ...)" when set; for the
115        // `message` field we want the kind portion only, so render kind
116        // without the operator suffix. `KindDisplay`'s Serialize impl streams
117        // the Display straight into the output via `collect_str`, avoiding an
118        // intermediate heap `String`.
119        map.serialize_entry("message", &KindDisplay(&self.kind))?;
120        match &self.kind {
121            ErrorKind::VariableNotFound(name) => map.serialize_entry("variable", name)?,
122            ErrorKind::InvalidContextLevel(level) => map.serialize_entry("level", level)?,
123            ErrorKind::Thrown(value) => map.serialize_entry("thrown", value)?,
124            ErrorKind::IndexOutOfBounds { index, length } => {
125                map.serialize_entry("index", index)?;
126                map.serialize_entry("length", length)?;
127            }
128            _ => {}
129        }
130        if let Some(op) = self.operator() {
131            map.serialize_entry("operator", op)?;
132        }
133        let ids = self.node_ids();
134        if !ids.is_empty() {
135            map.serialize_entry("node_ids", ids)?;
136        }
137        map.end()
138    }
139}
140
141/// Render an [`ErrorKind`] without the operator suffix. Used by
142/// [`Error::serialize`] to populate the `message` field.
143struct KindDisplay<'a>(&'a ErrorKind);
144
145impl<'a> fmt::Display for KindDisplay<'a> {
146    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
147        write_kind_message(f, self.0)
148    }
149}
150
151impl Serialize for KindDisplay<'_> {
152    /// Stream the kind message straight into the serializer via `collect_str`
153    /// instead of allocating an intermediate `String` with `to_string()`.
154    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
155        serializer.collect_str(self)
156    }
157}