1use thiserror::Error;
4
5#[derive(Error, Debug)]
7pub enum ToonError {
8 #[error("JSON parsing error: {0}")]
10 JsonError(#[from] serde_json::Error),
11
12 #[error("TOON parsing error at line {line}: {message}")]
14 ParseError {
15 line: usize,
17 message: String,
19 },
20
21 #[error("Serialization error: {0}")]
23 SerializeError(String),
24
25 #[error("Invalid tabular array: {0}")]
27 InvalidTabularArray(String),
28}
29
30impl ToonError {
31 pub fn parse_error(line: usize, message: impl Into<String>) -> Self {
33 ToonError::ParseError {
34 line,
35 message: message.into(),
36 }
37 }
38
39 pub fn serialize_error(message: impl Into<String>) -> Self {
41 ToonError::SerializeError(message.into())
42 }
43
44 pub fn invalid_tabular_array(message: impl Into<String>) -> Self {
46 ToonError::InvalidTabularArray(message.into())
47 }
48}
49
50pub 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}