Skip to main content

rust_json_parser/
error.rs

1use std::fmt;
2
3/// Represents errors encountered while tokenizing or parsing JSON.
4///
5/// Each variant identifies a specific parsing failure and
6/// includes information about where the error occurred.
7#[derive(Debug, Clone, PartialEq)]
8pub enum JsonError {
9    /// Occurs when the parser encounters a token that was not expected.
10    ///
11    /// For example, an invalid character such as `@` in JSON input.
12    UnexpectedToken {
13        expected: String,
14        found: String,
15        position: usize,
16    },
17
18    /// Occurs when JSON input ends before a required token is found.
19    ///
20    /// For example, an array missing its closing bracket.
21    UnexpectedEndOfInput { expected: String, position: usize },
22
23    /// Occurs when a JSON number has an invalid format.
24    ///
25    /// For example, a number with an invalid decimal or exponent.
26    InvalidNumber { value: String, position: usize },
27
28    /// Occurs when a JSON string contains an unsupported escape sequence.
29    ///
30    /// For example, `\q` is not a valid JSON escape sequence.
31    InvalidEscape { char: char, position: usize },
32
33    /// Occurs when a JSON string contains an invalid Unicode escape.
34    ///
35    /// For example, `\uZZZZ` is not a valid Unicode escape.
36    InvalidUnicode { sequence: String, position: usize },
37}
38impl fmt::Display for JsonError {
39    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40        match self {
41            JsonError::UnexpectedToken {
42                expected,
43                found,
44                position,
45            } => {
46                write!(
47                    f,
48                    "Unexpected token at position {}: expected {}, found {}",
49                    position, expected, found
50                )
51            }
52            JsonError::UnexpectedEndOfInput { expected, position } => {
53                write!(
54                    f,
55                    "Unexpected end of Input at position {}: expected {}",
56                    position, expected
57                )
58            }
59            JsonError::InvalidNumber { value, position } => {
60                write!(
61                    f,
62                    "Invalid number at position {}: value {}",
63                    position, value
64                )
65            }
66            JsonError::InvalidEscape { char, position } => {
67                write!(
68                    f,
69                    "Invalid escape character '{}' at position {}",
70                    char, position
71                )
72            }
73            JsonError::InvalidUnicode { sequence, position } => {
74                write!(
75                    f,
76                    "Invalid Unicode sequence '{}' at position {}",
77                    sequence, position
78                )
79            }
80        }
81    }
82}
83
84impl std::error::Error for JsonError {}
85
86#[cfg(test)]
87mod tests {
88    use super::*;
89
90    #[test]
91    fn test_error_creation() {
92        let error = JsonError::UnexpectedToken {
93            expected: "number".to_string(),
94            found: "@".to_string(),
95            position: 5,
96        };
97
98        assert!(format!("{:?}", error).contains("UnexpectedToken"));
99    }
100    #[test]
101    fn test_error_variants() {
102        let token_error = JsonError::UnexpectedToken {
103            expected: "number".to_string(),
104            found: "x".to_string(),
105            position: 3,
106        };
107
108        let eof_error = JsonError::UnexpectedEndOfInput {
109            expected: "closing quote".to_string(),
110            position: 10,
111        };
112
113        let num_error = JsonError::InvalidNumber {
114            value: "12.34.56".to_string(),
115            position: 0,
116        };
117
118        assert!(!format!("{:?}", token_error).is_empty());
119        assert!(!format!("{:?}", eof_error).is_empty());
120        assert!(!format!("{:?}", num_error).is_empty());
121    }
122    #[test]
123    fn test_error_display() {
124        let error = JsonError::UnexpectedToken {
125            expected: "valid JSON".to_string(),
126            found: "@".to_string(),
127            position: 0,
128        };
129
130        let message = format!("{}", error);
131        assert!(message.contains("position 0"));
132        assert!(message.contains("valid JSON"));
133        assert!(message.contains("@"));
134    }
135    #[test]
136    fn test_invalid_escape_display() {
137        let err = JsonError::InvalidEscape {
138            char: 'q',
139            position: 5,
140        };
141        let msg = format!("{}", err);
142        assert!(msg.contains("escape"));
143        assert!(msg.contains("q"));
144    }
145    #[test]
146    fn test_invalid_unicode_display() {
147        let err = JsonError::InvalidUnicode {
148            sequence: "00GG".to_string(),
149            position: 3,
150        };
151        let msg = format!("{}", err);
152        assert!(msg.contains("unicode") || msg.contains("Unicode"));
153    }
154    #[test]
155    fn test_error_is_std_error() {
156        let err = JsonError::InvalidEscape {
157            char: 'x',
158            position: 0,
159        };
160        let _: &dyn std::error::Error = &err;
161    }
162}