Skip to main content

cadlib/
error.rs

1//! Error types for the cadlib bindings.
2
3use serde::Deserialize;
4
5/// An error returned by the cadlib native library, or by the bindings layer.
6#[derive(Debug, Clone)]
7pub enum CadLibError {
8    /// A known, anticipated CAD error: a machine-readable `error_code` plus
9    /// structured `error_details`.
10    Expected {
11        /// Machine-readable error identifier.
12        error_code: String,
13        /// Structured context for the error (shape depends on `error_code`).
14        error_details: serde_json::Value,
15    },
16    /// An unexpected internal error from the library, or a bindings-side failure
17    /// (parameter marshalling, result decoding, or an interior NUL byte).
18    Unexpected {
19        /// Human-readable description.
20        message: String,
21    },
22}
23
24impl std::fmt::Display for CadLibError {
25    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
26        match self {
27            Self::Expected { error_code, .. } => write!(f, "expected cad lib error: {error_code}"),
28            Self::Unexpected { message } => write!(f, "{message}"),
29        }
30    }
31}
32
33impl std::error::Error for CadLibError {}
34
35/// Mirrors the JSON error payload.
36#[derive(Deserialize)]
37#[serde(tag = "kind", rename_all = "lowercase")]
38enum CadErrorPayload {
39    Expected {
40        error_code: String,
41        #[serde(default)]
42        error_details: serde_json::Value,
43    },
44    Unexpected {
45        message: String,
46    },
47}
48
49/// Decode the JSON error payload from the FFI into a [`CadLibError`]. Falls back
50/// to [`CadLibError::Unexpected`] when the message is not the expected JSON shape.
51pub(crate) fn parse_cad_error(raw: &str) -> CadLibError {
52    match serde_json::from_str::<CadErrorPayload>(raw) {
53        Ok(CadErrorPayload::Expected {
54            error_code,
55            error_details,
56        }) => CadLibError::Expected {
57            error_code,
58            error_details,
59        },
60        Ok(CadErrorPayload::Unexpected { message }) => CadLibError::Unexpected { message },
61        Err(_) => CadLibError::Unexpected {
62            message: raw.to_string(),
63        },
64    }
65}