easy_err/
err.rs

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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
use std::{error, fmt, fs::OpenOptions, io::{self, Write}, path::Path};

use colored::Colorize;
pub use chrono::{DateTime, Local};


/// 用于统一错误的枚举
/// 
/// # Examples
/// ``` 
/// let err = easy_err::Error::custom("Here is a error.");
/// err.report();
/// ```
#[derive(Debug)]
pub enum Error {
	/// 用于包装已经实现Error Trait的结构体或枚举
	Basic(DateTime<Local>, Box<dyn error::Error>),
	/// 用于报告用户自定义的错误信息
	Custom(DateTime<Local>, String)
}

impl Error {
	/// 获取错误发生的时间
	/// 
	/// # Example
	/// ```
	/// let time = easy_err::Error::custom("Here is a custom error.").time();
	/// println!("{}", time);
	/// ```
	pub fn time(&self) -> DateTime<Local> {
		match self {
			Self::Basic(time, _) => *time,
			Self::Custom(time, _) => *time
		}
	}

	/// 产生一个basic变体
	/// 
	/// # Examples
	/// ```
	/// let file = std::fs::File::open("An obvious mistake.").or_else(|err|{Err(easy_err::Error::basic(err))});
	/// match file {
	/// 	Ok(_) => println!("Ok!"),
	/// 	Err(err) => {err.report();}
	/// }
	/// ```
	pub fn basic(err: impl error::Error + 'static) -> Error {
		Error::Basic(Local::now(), Box::new(err))
	}

	/// 产生一个custom变体
	/// 
	/// # Examples
	/// ```
	/// let custom_err = easy_err::Error::custom("Here is a error.");
	/// custom_err.report();
	/// ```
	pub fn custom<S>(msg: S) -> Error where S:ToString{
		Error::Custom(Local::now(), msg.to_string())
	}

	/// 在标准错误流中输出一条报告信息
	/// 
	/// # Examples
	/// ```
	/// let custom_err = easy_err::Error::custom("Here is a error.");
	/// custom_err.report();
	/// // output:
	/// // error:
	/// //     time: <ErrorTime>
	/// //      msg: 'Here is a error.'
	/// ```
	pub fn report(&self) -> &Self {
		eprintln!("{}: {}", "error".red().bold(), self);
		self
	}

	/// 引发 panic!() 宏
	/// 
	/// # Examples
	/// ```
	/// let custom_err = easy_err::Error::custom("Here is a error.");
	/// custom_err.panic(); 
	/// // output:
	/// // error:
	/// //     time: <ErrorTime>
	/// //      msg: 'Here is a error.'
	/// ```
	pub fn panic(&self){
		panic!("{}", self);
	}

	/// 将报告信息输出至文件
	/// 
	/// # Params
	/// - path: 任何可以转换为 Path 的值
	/// 
	/// # Examples
	/// ```
	/// let custom_err = easy_err::Error::custom("Here is a error.");
	/// custom_err.log_to("./log.txt");
	/// ```
	pub fn log_to<P>(&self, path: P) -> &Self where P: AsRef<Path> {
		match OpenOptions::new().create(true).append(true).open(path) {
			Ok(mut file) => {
				if let Err(err) = writeln!(file, "error:{}", self) {
					Error::basic(err).report();
				}
			}
			Err(err) => {Error::basic(err).report();}
		}
		self
	}
}

impl fmt::Display for Error {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		match self {
			Self::Basic(time, err) => write!(f, "\n\ttime: {}\n\t msg: {}\n", time, err),
			Self::Custom(time, msg) => write!(f, "\n\ttime: {}\n\t msg: {}\n", time, msg)
		}
	}
}

impl error::Error for Error {
	fn source(&self) -> Option<&(dyn error::Error + 'static)> {
		match self {
			Self::Basic(.., err) => Some(err.as_ref()),
			Self::Custom(..) => None
		}
	}
}

impl From<io::Error> for Error {
	fn from(value: io::Error) -> Self {
		Self::basic(value)
	}
}

impl From<fmt::Error> for Error {
	fn from(value: fmt::Error) -> Self {
		Self::basic(value)
	}
}

/// 用于方便地将Result<T, Error>当作Error处理
/// 
/// # Tips
/// - 不建议为别的结构体或枚举实现此Trait,因为我自己还没完全搞清楚这个地方该怎么弄,这暂且还是一个实验性功能
/// 
/// # Example
/// ```
/// use std::fs;
/// use easy_err::{Error, ErrResult};
/// 
/// fn test() -> Result<(), Error> {
/// 	fs::File::open("An obvious mistake.")?;
/// 	Ok(())
/// }
/// 
/// test().panic();
/// ```
pub trait ErrResult<T> {
	fn panic(self: Self) -> T;
}

impl<T> ErrResult<T> for Result<T, Error> {
	fn panic(self) -> T {
		match self {
			Ok(t) => t,
			Err(err) => panic!("{}", err.to_string())
		}
	}
}