summaryrefslogtreecommitdiffstats
path: root/src/error/error_type.rs
blob: 4913d76a7c50b7ad0ae12cc0a6c5aba9ba36aec0 (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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
use std::convert::From;
use std::io;

use super::AppErrorKind;

#[derive(Clone, Debug)]
pub struct AppError {
    _kind: AppErrorKind,
    _cause: String,
}

impl AppError {
    pub fn new(_kind: AppErrorKind, _cause: String) -> Self {
        Self { _kind, _cause }
    }

    pub fn error(cause: impl ToString) -> Self {
        Self::new(AppErrorKind::UnknownError, cause.to_string())
    }

    pub fn fail<T>(cause: impl ToString) -> Result<T, AppError> {
        Err(Self::error(cause))
    }

    #[allow(dead_code)]
    pub fn kind(&self) -> &AppErrorKind {
        &self._kind
    }
}

impl std::fmt::Display for AppError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{}", self._cause)
    }
}

impl From<io::Error> for AppError {
    fn from(err: io::Error) -> Self {
        let cause = err.to_string();
        Self {
            _kind: AppErrorKind::from(err.kind()),
            _cause: cause,
        }
    }
}

impl From<globset::Error> for AppError {
    fn from(err: globset::Error) -> Self {
        let cause = err.to_string();
        Self {
            _kind: AppErrorKind::from(err.kind()),
            _cause: cause,
        }
    }
}

impl From<regex::Error> for AppError {
    fn from(err: regex::Error) -> Self {
        let cause = err.to_string();
        Self {
            _kind: AppErrorKind::Regex,
            _cause: cause,
        }
    }
}

impl From<std::env::VarError> for AppError {
    fn from(err: std::env::VarError) -> Self {
        let cause = err.to_string();
        Self {
            _kind: AppErrorKind::from(err),
            _cause: cause,
        }
    }
}

impl From<toml::de::Error> for AppError {
    fn from(err: toml::de::Error) -> Self {
        let cause = err.to_string();
        Self {
            _kind: AppErrorKind::from(err),
            _cause: cause,
        }
    }
}