Skip to main content

web_scrape/
error.rs

1use crate::scrape::ScrapeError;
2use clerr::Report;
3use reqwest::StatusCode;
4use std::fmt::{Display, Formatter};
5use std::string::FromUtf8Error;
6use web_url::WebUrl;
7
8/// An error scraping data from the web.
9#[derive(Debug)]
10pub enum Error {
11    /// An uncategorized error.
12    Other(Report),
13
14    /// The web data was not properly UTF-8 encoded.
15    InvalidString(FromUtf8Error),
16
17    /// The response status code was invalid.
18    InvalidResponseStatus(StatusCode),
19
20    /// The URL was invalid.
21    InvalidURL { url: WebUrl, error_message: String },
22
23    /// There was an error reading or writing the cache.
24    Cache(file_storage::Error),
25
26    /// There was an error sourcing the data.
27    Source(reqwest::Error),
28
29    /// There was an error scraping the data.
30    Scrape(ScrapeError),
31}
32
33impl From<Report> for Error {
34    fn from(report: Report) -> Self {
35        Self::Other(report)
36    }
37}
38
39impl From<FromUtf8Error> for Error {
40    fn from(error: FromUtf8Error) -> Self {
41        Self::InvalidString(error)
42    }
43}
44
45impl From<file_storage::Error> for Error {
46    fn from(error: file_storage::Error) -> Self {
47        Self::Cache(error)
48    }
49}
50
51impl From<reqwest::Error> for Error {
52    fn from(error: reqwest::Error) -> Self {
53        Self::Source(error)
54    }
55}
56
57impl From<ScrapeError> for Error {
58    fn from(error: ScrapeError) -> Self {
59        Self::Scrape(error)
60    }
61}
62
63impl Display for Error {
64    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
65        match self {
66            Self::Other(report) => write!(f, "{}", report),
67            Self::InvalidString(error) => write!(f, "invalid utf-8 string: {}", error),
68            Self::InvalidResponseStatus(status) => {
69                write!(f, "invalid response status: {}", status)
70            }
71            Self::InvalidURL { url, error_message } => {
72                write!(f, "invalid url '{}': {}", url, error_message)
73            }
74            Self::Cache(error) => write!(f, "cache error: {}", error),
75            Self::Source(error) => write!(f, "source error: {}", error),
76            Self::Scrape(error) => write!(f, "scrape error: {}", error),
77        }
78    }
79}
80
81impl std::error::Error for Error {
82    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
83        match self {
84            Self::InvalidString(error) => Some(error),
85            Self::Cache(error) => Some(error),
86            Self::Source(error) => Some(error),
87            Self::Scrape(error) => Some(error),
88            _ => None,
89        }
90    }
91}