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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
use std::{
    error::Error,
    io,
    num::{ParseIntError, TryFromIntError},
    path::{PathBuf, StripPrefixError},
};

use thiserror::Error;

pub type Result<T> = std::result::Result<T, ThermiteError>;

#[derive(Error, Debug)]
pub enum ThermiteError {
    #[error("No such file {0:?}")]
    MissingFile(Box<PathBuf>),
    #[error(transparent)]
    IoError(#[from] io::Error),
    #[error("{0}")]
    UnknownError(String),
    #[error("Error making network request: {0}")]
    NetworkError(Box<ureq::Error>),
    #[error(transparent)]
    ZipError(#[from] zip::result::ZipError),
    #[error("Error parsing JSON: {0}")]
    JsonError(Box<dyn Error + Send + Sync + 'static>),
    #[error("Error resolving dependency {0}")]
    DepError(String),
    #[error("Error stripping directory prefix {0}\nIs the mod formatted correctly?")]
    PrefixError(#[from] StripPrefixError),
    #[error("Sanity check failed")]
    SanityError,
    #[error("Attempted to save a file but the path was None")]
    MissingPath,
    #[error("Error converting string to integer: {0}")]
    ParseIntError(#[from] ParseIntError),
    #[error("Unable to convert integer: {0}")]
    IntConversionError(#[from] TryFromIntError),
    #[error("Error parsing mod name: {0}")]
    NameError(String),
    #[error("Expected string to be UTF8")]
    UTF8Error,
}

// ureq::Error is ~240 bytes so we store it in a box
impl From<ureq::Error> for ThermiteError {
    fn from(value: ureq::Error) -> Self {
        Self::NetworkError(Box::new(value))
    }
}

impl From<json5::Error> for ThermiteError {
    fn from(value: json5::Error) -> Self {
        Self::JsonError(value.into())
    }
}

impl From<serde_json::Error> for ThermiteError {
    fn from(value: serde_json::Error) -> Self {
        Self::JsonError(value.into())
    }
}

#[cfg(test)]
mod test {
    use ureq::ErrorKind;

    use super::ThermiteError;

    #[test]
    fn from_ureq() {
        let err = ureq::get("http://your_mother:8008").call().expect_err("How");

        let thermite_err = ThermiteError::from(err);
        
        if let ThermiteError::NetworkError(u) = thermite_err {
            assert_eq!(u.kind(), ErrorKind::Dns);
        } else {
            panic!("Unexpected error type: {:?}", thermite_err);
        }
    }

}