Skip to main content

jzon/
error.rs

1use std::fmt;
2
3#[non_exhaustive]
4#[derive(Debug, Clone, PartialEq)]
5pub enum Error {
6    UnexpectedEof,
7    UnexpectedToken,
8    MissingField(&'static str),
9    InvalidNumber,
10    InvalidUtf8,
11    InvalidEscape,
12    UnknownField,
13    UnknownVariant,
14    /// A `&str` field requested zero-copy but the JSON string has escape
15    /// sequences — use `String` for that field to allow allocated unescaping.
16    EscapedString,
17    /// An object key contained escape sequences (extremely rare).
18    EscapedKey,
19    Custom(String),
20}
21
22impl fmt::Display for Error {
23    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
24        match self {
25            Error::UnexpectedEof    => write!(f, "unexpected end of JSON input"),
26            Error::UnexpectedToken  => write!(f, "unexpected token in JSON input"),
27            Error::MissingField(n)  => write!(f, "missing JSON field `{n}`"),
28            Error::InvalidNumber    => write!(f, "invalid JSON number"),
29            Error::InvalidUtf8      => write!(f, "invalid UTF-8 in JSON string"),
30            Error::InvalidEscape    => write!(f, "invalid JSON escape sequence"),
31            Error::UnknownField     => write!(f, "unknown JSON field (deny_unknown_fields)"),
32            Error::UnknownVariant   => write!(f, "unknown enum variant"),
33            Error::EscapedString    => write!(
34                f,
35                "string contains escape sequences — borrow is impossible; use `String`"
36            ),
37            Error::EscapedKey       => write!(f, "JSON object key contains escape sequences"),
38            Error::Custom(m)        => write!(f, "{m}"),
39        }
40    }
41}
42
43impl std::error::Error for Error {}