use std::borrow::Cow;
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum XmlError {
#[error("malformed XML: {0}")]
Syntax(#[from] quick_xml::Error),
#[error("XML is not valid UTF-8: {0}")]
Utf8(#[from] std::str::Utf8Error),
#[error("expected root element <{expected}>, found <{found}>")]
UnexpectedRoot {
expected: &'static str,
found: String,
},
#[error("XML document has no root element")]
NoRoot,
#[error("{ty} is missing required <{field}>")]
MissingField {
ty: &'static str,
field: &'static str,
},
#[error("{ty} has unexpected element <{name}>")]
UnknownElement { ty: &'static str, name: String },
#[error("{ty} has duplicate element <{name}>")]
DuplicateElement { ty: &'static str, name: String },
#[error("{ty} has unexpected text content")]
UnexpectedText { ty: &'static str },
#[error("<{element}> must contain only text, found child <{child}>")]
UnexpectedChild { element: String, child: String },
#[error("invalid {ty} value {value:?}: {reason}")]
InvalidValue {
ty: &'static str,
value: String,
reason: Cow<'static, str>,
},
#[error("unknown entity reference &{0};")]
UnknownEntity(String),
#[error("unexpected end of XML document")]
UnexpectedEof,
#[error("failed to write XML: {0}")]
Io(#[from] std::io::Error),
}
impl XmlError {
pub(crate) fn invalid(
ty: &'static str,
value: &str,
reason: impl Into<Cow<'static, str>>,
) -> Self {
Self::InvalidValue {
ty,
value: value.to_owned(),
reason: reason.into(),
}
}
}
impl From<quick_xml::events::attributes::AttrError> for XmlError {
fn from(err: quick_xml::events::attributes::AttrError) -> Self {
Self::Syntax(err.into())
}
}