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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
use std::error;
use std::ffi::NulError;
use std::fmt::{self, Display, Formatter};
use std::io;
use std::result::Result as StdResult;
const FAILURE: i32 = 1;
pub type Result<T> = StdResult<T, Error>;
#[derive(Debug)]
pub enum ErrorKind {
Args,
InsufficientQuery,
InvalidUnicode,
IO,
Terminal,
Exec,
NulError,
}
#[derive(Debug)]
pub struct Error {
pub(crate) message: String,
pub kind: ErrorKind,
pub source: Option<Box<dyn error::Error>>,
pub exit_code: i32,
}
impl Display for Error {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
Display::fmt(&self.message, f)
}
}
impl error::Error for Error {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
self.source.as_deref()
}
}
impl Error {
pub fn args(message: &str) -> Self {
Self {
message: message.to_string(),
kind: ErrorKind::Args,
source: None,
exit_code: FAILURE,
}
}
pub fn insufficient_query(message: &str) -> Self {
Self {
message: message.to_string(),
kind: ErrorKind::InsufficientQuery,
source: None,
exit_code: FAILURE,
}
}
pub fn invalid_unicode(message: &str) -> Self {
Self {
message: message.to_string(),
kind: ErrorKind::InvalidUnicode,
source: None,
exit_code: FAILURE,
}
}
pub fn exec(message: &str) -> Self {
Self {
message: message.to_string(),
kind: ErrorKind::Exec,
source: None,
exit_code: FAILURE,
}
}
}
impl From<io::Error> for Error {
fn from(error: io::Error) -> Self {
Self {
message: format!(
"Unhandled IO error happened. See the details from .source: {}",
error
),
kind: ErrorKind::IO,
source: Some(Box::new(error)),
exit_code: FAILURE,
}
}
}
impl From<NulError> for Error {
fn from(error: NulError) -> Self {
Self {
message: format!(
"The string contains nul bytes. See the details from .source: {}",
error
),
kind: ErrorKind::NulError,
source: Some(Box::new(error)),
exit_code: FAILURE,
}
}
}