Skip to main content

json_schema_rs/json_schema/
error.rs

1//! Errors when parsing JSON Schema.
2
3use std::fmt;
4
5/// Result type for JSON Schema parsing operations.
6pub type JsonSchemaParseResult<T> = Result<T, JsonSchemaParseError>;
7
8/// Error when parsing a JSON Schema with the given settings.
9#[derive(Debug)]
10pub enum JsonSchemaParseError {
11    /// JSON or serde error (invalid JSON, wrong types, etc.).
12    Serde(serde_json::Error),
13    /// An unknown key was present and strict ingestion was enabled.
14    UnknownField {
15        /// The unknown key name.
16        key: String,
17        /// JSON Pointer or path to the schema object that contained the key.
18        path: String,
19    },
20    /// I/O error when reading from a reader or file.
21    Io(std::io::Error),
22}
23
24impl fmt::Display for JsonSchemaParseError {
25    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
26        match self {
27            JsonSchemaParseError::Serde(e) => write!(f, "invalid JSON Schema: {e}"),
28            JsonSchemaParseError::UnknownField { key, path } => {
29                write!(f, "unknown schema key \"{key}\" at {path}")
30            }
31            JsonSchemaParseError::Io(e) => write!(f, "io error: {e}"),
32        }
33    }
34}
35
36impl std::error::Error for JsonSchemaParseError {
37    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
38        match self {
39            JsonSchemaParseError::Serde(e) => Some(e),
40            JsonSchemaParseError::UnknownField { .. } => None,
41            JsonSchemaParseError::Io(e) => Some(e),
42        }
43    }
44}
45
46impl From<serde_json::Error> for JsonSchemaParseError {
47    fn from(e: serde_json::Error) -> Self {
48        JsonSchemaParseError::Serde(e)
49    }
50}
51
52impl From<std::io::Error> for JsonSchemaParseError {
53    fn from(e: std::io::Error) -> Self {
54        JsonSchemaParseError::Io(e)
55    }
56}