json_node/errors/
json_node_error.rs

1use std::{error::Error, fmt::Display};
2
3pub type Result<T> = std::result::Result<T, JsonNodeError>;
4
5/// An error that can occur when parsing a JSON node.
6#[derive(Debug, PartialEq, Clone)]
7pub enum JsonNodeError {
8    /// The JSON string is empty or has only white space.
9    /// If the `Option<String>` is `Some`, then the current node has a parent node which is the string.
10    EmptyJson(Option<Box<String>>),
11
12    /// The JSON string could not be parsed.
13    /// The `String` is the JSON string that could not be parsed.
14    CouldntParseNode(String),
15
16    /// The JSON object has multiple properties with the same key.
17    /// The `String` is the key that is duplicated.
18    MultiplePropertiesWithSameKey(String),
19
20    /// The JSON object does not have a property with the given key.
21    /// The `String` is the key that was not found.
22    KeyNotFound(String),
23}
24
25impl Display for JsonNodeError {
26    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
27        match self {
28            JsonNodeError::EmptyJson(parent_node) => {
29                if let Some(parent_node) = parent_node {
30                    return write!(f, "{}", parent_node);
31                }
32                
33                write!(f, "{}", "Json node has no parent".to_string())
34            },
35            JsonNodeError::CouldntParseNode(node) => write!(f, "{}", node),
36            JsonNodeError::MultiplePropertiesWithSameKey(key) => write!(f, "{}", key),
37            JsonNodeError::KeyNotFound(key) => write!(f, "{}", key),
38        }
39    }
40}
41
42impl Error for JsonNodeError {}