1use std::{error::Error, io::Error as IOError, str::Utf8Error, string::FromUtf8Error};
2use xmlparser::Error as ParserError;
3
4#[derive(Debug)]
5pub enum XmlError {
6 IO(IOError),
7 Parser(ParserError),
8 Utf8(Utf8Error),
9 UnexpectedEof,
10 UnexpectedToken { token: String },
11 TagMismatch { expected: String, found: String },
12 MissingField { name: String, field: String },
13 UnknownField { name: String, field: String },
14 UnterminatedEntity { entity: String },
15 UnrecognizedSymbol { symbol: String },
16 FromStr(Box<dyn Error + Send + Sync>),
21}
22
23impl XmlError {
24 pub fn extended_error(&self) -> Option<&crate::XmlExtendedError> {
25 let XmlError::FromStr(err) = self else {
26 return None
27 };
28 err.downcast_ref()
29 }
30}
31
32impl From<IOError> for XmlError {
33 fn from(err: IOError) -> Self {
34 XmlError::IO(err)
35 }
36}
37
38impl From<Utf8Error> for XmlError {
39 fn from(err: Utf8Error) -> Self {
40 XmlError::Utf8(err)
41 }
42}
43
44impl From<FromUtf8Error> for XmlError {
45 fn from(err: FromUtf8Error) -> Self {
46 XmlError::Utf8(err.utf8_error())
47 }
48}
49
50impl From<ParserError> for XmlError {
51 fn from(err: ParserError) -> Self {
52 XmlError::Parser(err)
53 }
54}
55
56impl From<crate::XmlExtendedError> for XmlError {
57 fn from(err: crate::XmlExtendedError) -> Self {
58 XmlError::FromStr(Box::new(err))
59 }
60}
61
62pub type XmlResult<T> = Result<T, XmlError>;
64
65impl Error for XmlError {
66 fn source(&self) -> Option<&(dyn Error + 'static)> {
67 use XmlError::*;
68 match self {
69 IO(e) => Some(e),
70 Parser(e) => Some(e),
71 Utf8(e) => Some(e),
72 FromStr(e) => Some(e.as_ref()),
73 _ => None,
74 }
75 }
76}
77
78impl std::fmt::Display for XmlError {
79 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
80 use XmlError::*;
81 match self {
82 IO(e) => write!(f, "I/O error: {}", e),
83 Parser(e) => write!(f, "XML parser error: {}", e),
84 Utf8(e) => write!(f, "invalid UTF-8: {}", e),
85 UnexpectedEof => f.write_str("unexpected end of file"),
86 UnexpectedToken { token } => write!(f, "unexpected token in XML: {:?}", token),
87 TagMismatch { expected, found } => write!(
88 f,
89 "mismatched XML tag; expected {:?}, found {:?}",
90 expected, found
91 ),
92 MissingField { name, field } => {
93 write!(f, "missing field in XML of {:?}: {:?}", name, field)
94 }
95 UnknownField { name, field } => {
96 write!(f, "unknown field {:?} in element {:?}", field, name)
97 }
98 UnterminatedEntity { entity } => write!(f, "unterminated XML entity: {}", entity),
99 UnrecognizedSymbol { symbol } => write!(f, "unrecognized XML symbol: {}", symbol),
100 FromStr(e) => write!(f, "error parsing XML value: {}", e),
101 }
102 }
103}