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 UnterminatedEntity { entity: String },
14 UnrecognizedSymbol { symbol: String },
15 FromStr(Box<dyn Error + Send + Sync>),
16}
17
18impl From<IOError> for XmlError {
19 fn from(err: IOError) -> Self {
20 XmlError::IO(err)
21 }
22}
23
24impl From<Utf8Error> for XmlError {
25 fn from(err: Utf8Error) -> Self {
26 XmlError::Utf8(err)
27 }
28}
29
30impl From<FromUtf8Error> for XmlError {
31 fn from(err: FromUtf8Error) -> Self {
32 XmlError::Utf8(err.utf8_error())
33 }
34}
35
36impl From<ParserError> for XmlError {
37 fn from(err: ParserError) -> Self {
38 XmlError::Parser(err)
39 }
40}
41
42pub type XmlResult<T> = Result<T, XmlError>;
44
45impl Error for XmlError {
46 fn source(&self) -> Option<&(dyn Error + 'static)> {
47 use XmlError::*;
48 match self {
49 IO(e) => Some(e),
50 Parser(e) => Some(e),
51 Utf8(e) => Some(e),
52 FromStr(e) => Some(e.as_ref()),
53 _ => None,
54 }
55 }
56}
57
58impl std::fmt::Display for XmlError {
59 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
60 use XmlError::*;
61 match self {
62 IO(e) => write!(f, "I/O error: {}", e),
63 Parser(e) => write!(f, "XML parser error: {}", e),
64 Utf8(e) => write!(f, "invalid UTF-8: {}", e),
65 UnexpectedEof => f.write_str("unexpected end of file"),
66 UnexpectedToken { token } => write!(f, "unexpected token in XML: {:?}", token),
67 TagMismatch { expected, found } => write!(
68 f,
69 "mismatched XML tag; expected {:?}, found {:?}",
70 expected, found
71 ),
72 MissingField { name, field } => {
73 write!(f, "missing field in XML of {:?}: {:?}", name, field)
74 }
75 UnterminatedEntity { entity } => write!(f, "unterminated XML entity: {}", entity),
76 UnrecognizedSymbol { symbol } => write!(f, "unrecognized XML symbol: {}", symbol),
77 FromStr(e) => write!(f, "error parsing XML value: {}", e),
78 }
79 }
80}