gitig/
error.rs

1use std::error;
2use std::{fmt, io};
3
4#[derive(Debug)]
5pub enum Error {
6    Io(io::Error),
7    Reqwest(reqwest::Error),
8    TemplateNotFound(Vec<String>),
9    ApplicationError(String),
10}
11
12impl Error {
13    pub const GENERIC_MSG: &str = "Failed to create .gitignore file";
14    pub const FETCH_TEMPLATE_FAILED_MSG: &str = "Failed to fetch templates";
15
16    pub fn generic() -> Self {
17        Error::ApplicationError(Self::GENERIC_MSG.to_owned())
18    }
19
20    pub fn fetch_templates_failed() -> Self {
21        Error::ApplicationError(Self::FETCH_TEMPLATE_FAILED_MSG.to_owned())
22    }
23}
24
25impl fmt::Display for Error {
26    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
27        match self {
28            Error::Io(e) => write!(f, "IO error: {}", e),
29            Error::Reqwest(e) => write!(f, "Reqwest error: {}", e),
30            Error::TemplateNotFound(t) => write!(f, "Template(s) not found: {}", t.join(", ")),
31            Error::ApplicationError(msg) => write!(f, "Application error: {}", msg),
32        }
33    }
34}
35
36impl error::Error for Error {
37    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
38        match self {
39            Error::Io(e) => Some(e),
40            Error::Reqwest(e) => Some(e),
41            Error::TemplateNotFound(_) => None,
42            Error::ApplicationError(_) => None,
43        }
44    }
45}
46
47impl From<io::Error> for Error {
48    fn from(e: io::Error) -> Self {
49        Error::Io(e)
50    }
51}
52
53impl From<reqwest::Error> for Error {
54    fn from(e: reqwest::Error) -> Self {
55        Error::Reqwest(e)
56    }
57}
58
59pub type Result<T> = std::result::Result<T, Error>;