codeforces_api/obj/
error.rs

1/// Error type for requests sent through this crate.
2///
3/// When sending a request is unsuccessful, a variant of the [`Error`] type
4/// will be returned.
5#[derive(Debug)]
6pub enum Error {
7    /// `Http` errors are a wrapper for network errors returned internally by
8    /// reqwest.
9    ///
10    /// This could be returned if, for example, the device is not connected to
11    /// the internet. Further documentation can be found with the
12    /// [`reqwest::Error`] type.
13    Http(reqwest::Error),
14    /// `Parse` errors are a wrapper for parsing errors returned internally by
15    /// reqwest.
16    ///
17    /// This could be returned if, for example, the Codeforces API returns
18    /// malformed JSON. Further documentation can be found with the
19    /// [`reqwest::Error`] type.
20    Parse(reqwest::Error),
21    /// `CodeforcesApi` errors are returned when the Codeforces API returns a
22    /// `status: FAILED` response, the comment field of the response is returned
23    /// as a [`String`]
24    CodeforcesApi(String),
25    /// `Testcases` errors are returned only when grabbing testcases which uses
26    /// webscraping internally since the Codeforces API does not provide it.
27    ///
28    /// For now, a simple message (`&'static str`) is returned, outlining the
29    /// error. However, in future, this could/should be moved into its own enum.
30    Testcases(&'static str),
31}
32
33/// Converting from a [`reqwest::Error`] is useful for quickly returning errors
34/// internally.
35impl From<reqwest::Error> for Error {
36    fn from(e: reqwest::Error) -> Self {
37        Error::Http(e)
38    }
39}
40
41/// Display the error with a short description of the error type as a prefix.
42impl std::fmt::Display for Error {
43    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
44        match self {
45            Error::Http(ref e) => write!(f, "HTTP: {}", e),
46            Error::Parse(ref e) => write!(f, "Parse: {}", e),
47            Error::CodeforcesApi(ref s) => write!(f, "Codeforces API: {}", s),
48            Error::Testcases(ref s) => write!(f, "User: {}", s),
49        }
50    }
51}
52
53/// Standard error impl for custom error type.
54impl std::error::Error for Error {
55    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
56        match self {
57            Error::Http(ref e) => Some(e),
58            Error::Parse(ref e) => Some(e),
59            Error::CodeforcesApi(_) => None,
60            Error::Testcases(_) => None,
61        }
62    }
63}