Skip to main content

feedparser_rs/
error.rs

1use std::fmt;
2use thiserror::Error;
3
4macro_rules! opaque_error {
5    ($(#[$meta:meta])* $name:ident($inner:ty)) => {
6        $(#[$meta])*
7        #[derive(Debug)]
8        pub struct $name($inner);
9
10        impl fmt::Display for $name {
11            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
12                self.0.fmt(f)
13            }
14        }
15
16        impl std::error::Error for $name {
17            fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
18                Some(&self.0)
19            }
20        }
21    };
22}
23
24opaque_error! {
25    /// An XML syntax error reported by the underlying reader.
26    ///
27    /// The reader's error type is not part of this crate's API; walk
28    /// [`std::error::Error::source`] for the original error.
29    XmlParseError(quick_xml::Error)
30}
31
32#[cfg(feature = "http")]
33opaque_error! {
34    /// A URL that could not be parsed.
35    ///
36    /// The parser's error type is not part of this crate's API; walk
37    /// [`std::error::Error::source`] for the original error.
38    UrlParseError(url::ParseError)
39}
40
41impl XmlParseError {
42    pub(crate) const fn new(inner: quick_xml::Error) -> Self {
43        Self(inner)
44    }
45}
46
47#[cfg(feature = "http")]
48impl Clone for UrlParseError {
49    fn clone(&self) -> Self {
50        Self(self.0)
51    }
52}
53
54#[cfg(feature = "http")]
55impl UrlParseError {
56    pub(crate) const fn new(inner: url::ParseError) -> Self {
57        Self(inner)
58    }
59}
60
61/// Feed parsing errors
62#[derive(Error, Debug)]
63#[non_exhaustive]
64pub enum FeedError {
65    /// XML parsing error
66    #[error("XML parsing error: {0}")]
67    XmlError(#[source] XmlParseError),
68
69    /// I/O error
70    #[error("IO error: {0}")]
71    IoError(#[from] std::io::Error),
72
73    /// Invalid feed format
74    #[error("Invalid feed format: {0}")]
75    InvalidFormat(String),
76
77    /// Encoding error
78    #[error("Encoding error: {0}")]
79    EncodingError(String),
80
81    /// HTTP fetch failure
82    #[cfg(feature = "http")]
83    #[error("HTTP error: {0}")]
84    Fetch(#[from] crate::http::FetchError),
85
86    /// Unknown error
87    #[error("Unknown error: {0}")]
88    Unknown(String),
89}
90
91impl FeedError {
92    pub(crate) const fn xml(error: quick_xml::Error) -> Self {
93        Self::XmlError(XmlParseError::new(error))
94    }
95}
96
97/// Result type for feed parsing operations
98pub type Result<T> = std::result::Result<T, FeedError>;
99
100#[cfg(test)]
101mod tests {
102    use super::*;
103    use std::assert_matches;
104    use std::error::Error as StdError;
105
106    #[test]
107    fn test_error_display() {
108        let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "test");
109        let inner = io_err.to_string();
110        let err = FeedError::xml(quick_xml::Error::Io(std::sync::Arc::new(io_err)));
111        assert!(err.to_string().starts_with("XML parsing error: "));
112        assert!(err.to_string().contains(&inner));
113        assert_matches!(err, FeedError::XmlError(_));
114    }
115
116    #[test]
117    fn test_error_from_io() {
118        let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "file not found");
119        let feed_err = FeedError::from(io_err);
120        assert_matches!(feed_err, FeedError::IoError(_));
121    }
122
123    #[test]
124    fn test_result_type() {
125        #[expect(
126            clippy::unnecessary_wraps,
127            reason = "the test exercises the `Result` alias itself"
128        )]
129        fn get_result() -> Result<i32> {
130            Ok(42)
131        }
132        let result = get_result();
133        assert!(result.is_ok());
134        assert_eq!(result.expect("should be ok"), 42);
135
136        let error: Result<i32> = Err(FeedError::Unknown("test".to_string()));
137        assert!(error.is_err());
138    }
139
140    #[test]
141    fn typed_variants_expose_downcastable_source() {
142        let xml_err = FeedError::xml(quick_xml::Error::Io(std::sync::Arc::new(
143            std::io::Error::other("xml io failure"),
144        )));
145        let xml_source = StdError::source(&xml_err).expect("XmlError must carry a source");
146        let inner = xml_source
147            .source()
148            .expect("XmlParseError must expose the reader error");
149        assert!(inner.downcast_ref::<quick_xml::Error>().is_some());
150
151        let io_err = FeedError::from(std::io::Error::other("io failure"));
152        let io_source = StdError::source(&io_err).expect("IoError must carry a source");
153        assert!(io_source.downcast_ref::<std::io::Error>().is_some());
154    }
155}