1use std::fmt;
4
5pub type Result<T> = std::result::Result<T, JsonError>;
7
8#[derive(Debug, Clone, PartialEq)]
10pub enum JsonError {
11 UnexpectedEnd,
13 UnexpectedChar(char, usize),
15 ExpectedChar(char, usize),
17 ExpectedToken(&'static str, usize),
19 InvalidNumber(usize),
21 InvalidEscape(usize),
23 InvalidUnicode(usize),
25 InvalidUtf8,
27 MissingField(String),
29 UnknownVariant(String),
31 TypeMismatch {
33 expected: &'static str,
34 found: &'static str,
35 position: usize,
36 },
37 NestingTooDeep(usize),
39 Custom(String),
41}
42
43impl fmt::Display for JsonError {
44 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45 match self {
46 JsonError::UnexpectedEnd => write!(f, "unexpected end of JSON input"),
47 JsonError::UnexpectedChar(c, pos) => {
48 write!(f, "unexpected character '{}' at position {}", c, pos)
49 }
50 JsonError::ExpectedChar(c, pos) => write!(f, "expected '{}' at position {}", c, pos),
51 JsonError::ExpectedToken(token, pos) => {
52 write!(f, "expected {} at position {}", token, pos)
53 }
54 JsonError::InvalidNumber(pos) => write!(f, "invalid number at position {}", pos),
55 JsonError::InvalidEscape(pos) => {
56 write!(f, "invalid escape sequence at position {}", pos)
57 }
58 JsonError::InvalidUnicode(pos) => {
59 write!(f, "invalid unicode escape at position {}", pos)
60 }
61 JsonError::InvalidUtf8 => write!(f, "invalid UTF-8 encoding"),
62 JsonError::MissingField(field) => write!(f, "missing required field: {}", field),
63 JsonError::UnknownVariant(variant) => write!(f, "unknown variant: {}", variant),
64 JsonError::TypeMismatch {
65 expected,
66 found,
67 position,
68 } => {
69 write!(
70 f,
71 "type mismatch at position {}: expected {}, found {}",
72 position, expected, found
73 )
74 }
75 JsonError::NestingTooDeep(depth) => write!(f, "nesting too deep: {} levels", depth),
76 JsonError::Custom(msg) => write!(f, "{}", msg),
77 }
78 }
79}
80
81impl std::error::Error for JsonError {}