toon_core/
error.rs

1//! Error types for TOON-LD operations.
2
3use thiserror::Error;
4
5/// Errors that can occur during TOON-LD operations
6#[derive(Error, Debug)]
7pub enum ToonError {
8    /// Error parsing JSON input
9    #[error("JSON parsing error: {0}")]
10    JsonError(#[from] serde_json::Error),
11
12    /// Error parsing TOON-LD input
13    #[error("TOON parsing error at line {line}: {message}")]
14    ParseError {
15        /// Line number where the error occurred (1-based)
16        line: usize,
17        /// Description of the parsing error
18        message: String,
19    },
20
21    /// Error during serialization
22    #[error("Serialization error: {0}")]
23    SerializeError(String),
24
25    /// Invalid tabular array structure
26    #[error("Invalid tabular array: {0}")]
27    InvalidTabularArray(String),
28}
29
30impl ToonError {
31    /// Create a new parse error at the given line
32    pub fn parse_error(line: usize, message: impl Into<String>) -> Self {
33        ToonError::ParseError {
34            line,
35            message: message.into(),
36        }
37    }
38
39    /// Create a new serialization error
40    pub fn serialize_error(message: impl Into<String>) -> Self {
41        ToonError::SerializeError(message.into())
42    }
43
44    /// Create a new invalid tabular array error
45    pub fn invalid_tabular_array(message: impl Into<String>) -> Self {
46        ToonError::InvalidTabularArray(message.into())
47    }
48}
49
50/// Result type for TOON-LD operations
51pub type Result<T> = std::result::Result<T, ToonError>;
52
53#[cfg(test)]
54mod tests {
55    use super::*;
56
57    #[test]
58    fn test_parse_error_display() {
59        let err = ToonError::parse_error(42, "unexpected token");
60        assert_eq!(
61            err.to_string(),
62            "TOON parsing error at line 42: unexpected token"
63        );
64    }
65
66    #[test]
67    fn test_serialize_error_display() {
68        let err = ToonError::serialize_error("invalid value");
69        assert_eq!(err.to_string(), "Serialization error: invalid value");
70    }
71
72    #[test]
73    fn test_invalid_tabular_array_display() {
74        let err = ToonError::invalid_tabular_array("mismatched field count");
75        assert_eq!(
76            err.to_string(),
77            "Invalid tabular array: mismatched field count"
78        );
79    }
80
81    #[test]
82    fn test_json_error_conversion() {
83        let json_err = serde_json::from_str::<serde_json::Value>("invalid json").unwrap_err();
84        let toon_err: ToonError = json_err.into();
85        assert!(toon_err.to_string().starts_with("JSON parsing error:"));
86    }
87}