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 homedir::GetHomeError;
use reqwest::{Error as ReqwestError, Url};
use serde_json::Error as JsonError;
use std::fmt;
use std::io;
use std::path::PathBuf;
pub type AppResult<T> = Result<T, AppError>;
#[derive(Debug)]
pub enum AppError {
ConfigFileNotFound(PathBuf),
ConfigFileNotProvided,
ConfigParseError { source: JsonError, path: PathBuf },
IoError(io::Error),
RequestFailed { url: Url, source: ReqwestError },
InvalidResponse { url: Url, reason: String },
InvalidHttpHeader(String),
UnableToGetHomeDirectory(GetHomeError),
}
impl fmt::Display for AppError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::ConfigFileNotFound(path) => {
write!(f, "Config file not found: {}", path.display())
}
Self::ConfigFileNotProvided => {
write!(f, "Config file not provided")
}
Self::IoError(err) => write!(f, "I/O error: {}", err),
Self::ConfigParseError { path, .. } => {
write!(f, "Failed to parse config at {}", path.display())
}
Self::RequestFailed { url, .. } => write!(f, "Request to {} failed", url),
Self::InvalidResponse { url, reason } => {
write!(f, "Invalid response from {}: {}", url, reason)
},
Self::InvalidHttpHeader(message) => write!(f, "Invalid HTTP header configuration: {}", message),
Self::UnableToGetHomeDirectory(err) => {
write!(f, "Failed to get home directory: {}", err)
}
}
}
}
impl std::error::Error for AppError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::IoError(err) => Some(err),
Self::ConfigParseError { source, .. } => Some(source),
Self::RequestFailed { source, .. } => Some(source),
_ => None,
}
}
}
// Convenient conversions from library errors
impl From<io::Error> for AppError {
fn from(err: io::Error) -> Self {
Self::IoError(err)
}
}
impl From<ReqwestError> for AppError {
fn from(err: ReqwestError) -> Self {
let url = match err.url() {
Some(url) => url.clone(),
None => Url::parse("http://unknown.url").unwrap(),
};
Self::RequestFailed { url, source: err }
}
}
impl From<JsonError> for AppError {
fn from(err: JsonError) -> Self {
Self::ConfigParseError {
source: err,
path: PathBuf::from("unknown"), // Default path
}
}
}
|