biodivine_xml_doc/
error.rs

1use quick_xml::events::attributes::AttrError;
2use quick_xml::Error as XMLError;
3use std::sync::Arc;
4use std::{str::Utf8Error, string::FromUtf8Error};
5
6/// Wrapper around `std::Result`
7pub type Result<T> = std::result::Result<T, Error>;
8
9/// Error types
10#[derive(Debug)]
11pub enum Error {
12    /// [`std::io`] related error.
13    Io(Arc<std::io::Error>),
14    /// Decoding related error.
15    /// Maybe the XML declaration has an encoding value that it doesn't recognize,
16    /// or it doesn't match its actual encoding,
17    CannotDecode,
18    /// Assorted errors while parsing XML.
19    MalformedXML(String),
20    /// The container element cannot have a parent.
21    /// Use `element.is_container()` to check if it is a container before
22    /// assigning it to another parent.
23    ContainerCannotMove,
24    /// You need to call `element.detatch()` before assigning another parent.
25    HasAParent,
26}
27
28impl std::fmt::Display for Error {
29    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
30        match self {
31            Error::Io(err) => write!(f, "IO Error: {}", err),
32            Error::CannotDecode => write!(f, "Cannot decode XML"),
33            Error::MalformedXML(err) => write!(f, "Malformed XML: {}", err),
34            Error::ContainerCannotMove => write!(f, "Container element cannot move"),
35            Error::HasAParent => write!(
36                f,
37                "Element already has a parent. Call detatch() before changing parent."
38            ),
39        }
40    }
41}
42
43impl std::error::Error for Error {
44    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
45        match self {
46            Error::Io(err) => Some(err),
47            _ => None,
48        }
49    }
50}
51
52impl From<XMLError> for Error {
53    fn from(err: XMLError) -> Error {
54        match err {
55            XMLError::EndEventMismatch { expected, found } => Error::MalformedXML(format!(
56                "Closing tag mismatch. Expected {}, found {}",
57                expected, found,
58            )),
59            XMLError::Io(err) => Error::Io(err),
60            XMLError::NonDecodable(_) => Error::CannotDecode,
61            err => Error::MalformedXML(err.to_string()),
62        }
63    }
64}
65
66impl From<AttrError> for Error {
67    fn from(err: AttrError) -> Self {
68        Error::MalformedXML(err.to_string())
69    }
70}
71
72impl From<FromUtf8Error> for Error {
73    fn from(_: FromUtf8Error) -> Error {
74        Error::CannotDecode
75    }
76}
77impl From<Utf8Error> for Error {
78    fn from(_: Utf8Error) -> Error {
79        Error::CannotDecode
80    }
81}
82
83impl From<std::io::Error> for Error {
84    fn from(err: std::io::Error) -> Error {
85        Error::Io(Arc::new(err))
86    }
87}