summaryrefslogtreecommitdiff
path: root/src/error.rs
blob: f946f588e60238a783464210537aa18138115e87 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
use derive_more::From;

pub type Result<T> = core::result::Result<T, Error>;

#[derive(Debug, From)]
pub enum Error {
    InvalidPath,
    NotFound(String),
    Download {
        url: String,
        source: reqwest::Error,
    },
    InvalidAppImage,

    #[from]
    Io(std::io::Error),

    #[from]
    Json(serde_json::Error),

    #[from]
    Http(reqwest::Error),

    #[from]
    EnvVar(std::env::VarError),

    #[from]
    IndicatifTemplate(indicatif::style::TemplateError),
}

impl core::fmt::Display for Error {
    fn fmt(&self, fmt: &mut core::fmt::Formatter) -> core::result::Result<(), std::fmt::Error> {
        match self {
            Error::Io(e) => write!(fmt, "{e}"),
            Error::NotFound(name) => write!(fmt, "Application '{name}' not found"),
            Error::Json(e) => write!(fmt, "JSON error: {e}"),
            Error::Http(e) => write!(fmt, "HTTP error: {e}"),
            Error::EnvVar(e) => write!(fmt, "Environment variable error: {e}"),
            Error::InvalidPath => write!(fmt, "Invalid path provided"),
            Error::IndicatifTemplate(e) => write!(fmt, "Progress bar template error: {e}"),
            Error::Download { url, source } => {
                if source.is_timeout() {
                    write!(fmt, "Download timed out from: {url}")
                } else if source.is_connect() {
                    write!(fmt, "Failed to connect to: {url}")
                } else if let Some(status) = source.status() {
                    match status.as_u16() {
                        404 => write!(fmt, "AppImage not found at: {url}"),
                        403 => write!(fmt, "Access denied at: {url}"),
                        500..=599 => write!(fmt, "Server error when downloading from: {url}"),
                        _ => write!(fmt, "HTTP {status} error downloading from: {url}"),
                    }
                } else {
                    write!(fmt, "Failed to download from {url}: {source}")
                }
            }
            Error::InvalidAppImage => {
                write!(fmt, "Invalid AppImage")
            }
        }
    }
}

impl std::error::Error for Error {}