except_plugin/core/mod.rs
1//! # Exception Core
2//! ```txt
3//! @author:syf20020816@Outlook.com
4//! @date:2023/8/13
5//! @version:0.0.1
6//! @description:
7//! ```
8mod macros;
9mod e_msg;
10mod flex_impl;
11mod easy;
12mod null_pointer;
13mod builder;
14mod index;
15mod sql;
16mod unsupported;
17
18pub use easy::EasyException;
19pub use null_pointer::NullPointerException;
20pub use index::ArrayIndexOutOfBoundsException;
21pub use unsupported::UnSupportedOpException;
22pub use sql::SQLException;
23pub use flex_impl::*;
24pub use e_msg::*;
25pub use builder::*;
26
27use std::time::{Duration, SystemTime, UNIX_EPOCH};
28use std::error::Error;
29use std::fmt::{Debug, Display, Formatter};
30use crate::{display_err_impl, exception_impl};
31
32
33/// # Exception trait
34/// each exception should impl this trait
35/// - can convert
36/// - can change
37pub trait Exception: Error {
38 fn code(&self) -> u32;
39 fn msg(&self) -> &str;
40 fn level(&self) -> ExceptionLevel;
41 fn set_code(&mut self, code: u32) -> ();
42 fn set_msg(&mut self, msg: &str) -> ();
43 fn set_level(&mut self, level: ExceptionLevel) -> ();
44 fn get_type(&self) -> Exceptions;
45 fn timestamp(&self) -> Duration;
46}
47
48/// # Exceptions enum
49/// - Super(顶级异常):顶级异常只能用于简单的处理,实际上他并不能显式的知道程序到底有什么问题,需要更加具体的异常。它虽然是顶级异常,但却是最低级的异常。
50/// - NullPointerException(空指针异常):当代码尝试访问一个空对象的方法或属性时抛出。
51/// - ArrayIndexOutOfBoundsException(数组越界异常):当试图访问数组中不存在的索引位置时抛出。
52/// - IllegalArgStateException(非法参数|状态异常):当传递给方法的参数不符合要求或无效时抛出或对象的状态与调用方法的前提条件不符时抛出。
53/// - IOException(输入/输出异常):当发生与输入/输出操作相关的错误时抛出,如文件读写错误、网络连接问题等。
54/// - FileNotFoundException(文件未找到异常):当尝试打开或访问不存在的文件时抛出。
55/// - SQLException(SQL异常):与数据库操作相关的异常,如连接失败、SQL语句错误等。
56/// - InterruptedException(线程中断异常):当线程在等待或睡眠状态被中断时抛出。
57/// - ClassCastException(类转换异常):当试图将一个对象强制转换为其不兼容的类型时抛出。
58/// - UnsupportedOperationException(不支持的操作异常):当调用对象不支持的方法或操作时抛出。
59/// - Define(自定义异常):当自己定义非上访的异常时。
60#[derive(Debug, Clone, PartialEq)]
61pub enum Exceptions {
62 Super,
63 Easy,
64 NullPointer,
65 ArrayIndexOutOfBounds,
66 IllegalArgState,
67 IO,
68 FileNotFound,
69 SQL,
70 Interrupted,
71 ClassCast,
72 UnSupportedOperation,
73 Define,
74}
75
76impl Default for Exceptions{
77 fn default() -> Self {
78 Exceptions::Define
79 }
80}
81
82/// # Exception Code 异常码
83/// - common exception or supper exception should use 101
84/// - you may need to define exception code
85pub struct ExceptionCode(u32);
86
87impl ExceptionCode {
88 pub const COMMON: u32 = 101;
89 pub const SUPER: u32 = 102;
90 pub const NULL_POINTER: u32 = 1000;
91 pub const ARRAY_INDEX_OUT_OF: u32 = 1100;
92 pub const ILLEGAL_ARGUMENT: u32 = 1200;
93 pub const ILLEGAL_STATE: u32 = 1300;
94 pub const IO: u32 = 1400;
95 pub const FILE_NOT_FOUND: u32 = 1500;
96 pub const SQL: u32 = 1600;
97 pub const INTERRUPTED: u32 = 1700;
98 pub const CLASS_CAST: u32 = 1800;
99 pub const UNSUPPORTED_OPERATION: u32 = 1900;
100 /// 自定义异常码
101 pub fn define(&mut self, code: u32) -> ExceptionCode {
102 Self(code)
103 }
104}
105
106/// # Exception Error Level 异常等级
107///
108/// ExceptionLevel should match LoggerLevel to print or debug information
109///
110/// 异常等级可对应日志等级,对应进行输出
111/// ## description
112/// - Error == Fatal : panic or stop the project
113/// - Warn : can fix or panic | stop the project
114/// - Debug : for debugging
115/// - Info : default level
116/// - Trace : lowest level
117#[derive(Debug, Clone, PartialEq)]
118pub enum ExceptionLevel {
119 Error,
120 Fatal,
121 Warn,
122 Debug,
123 Info,
124 Trace,
125}
126
127impl Default for ExceptionLevel{
128 fn default() -> Self {
129 ExceptionLevel::Info
130 }
131}
132
133/// # Reason for UnSupported
134#[derive(Debug, PartialEq, Clone)]
135pub enum Reasons {
136 UnSupported(UnSupportedReasons),
137 SQL(SQLReasons),
138 Other(String),
139}
140
141impl Default for Reasons{
142 fn default() -> Self {
143 Reasons::Other(String::new())
144 }
145}
146
147#[derive(Debug, PartialEq, Clone)]
148pub enum UnSupportedReasons {
149 /// Illegal value
150 /// such as : a param need u32 , but get value < 0 or None(Option) or bigger than u32::MAX_VALUE
151 Value,
152 /// Illegal type
153 /// such as : a param need u32 , but get bool
154 Type,
155 /// thread block
156 Block,
157 /// cannot get lock
158 Lock,
159 /// cannot access
160 UnAccessible,
161 /// No permission to access
162 Auth,
163 /// IO
164 IO,
165 /// file not found
166 FileNotFound,
167 /// interrupt when thread waiting or sleeping
168 Interrupted,
169 /// conert error
170 ClassCast,
171 /// other reason
172 /// specific reasons need to be set on msg param
173 Other,
174}
175
176#[derive(Debug, PartialEq, Clone)]
177pub enum SQLReasons {
178 /// SQL statement error
179 Stmt,
180 /// SQL Logic error
181 Logic,
182 /// no Database
183 NO_DB,
184 /// no table exist
185 NO_Table,
186 /// no column
187 NO_Column,
188 /// no rows
189 NO_Rows,
190 /// empty
191 Empty,
192 /// no authorization
193 NO_Auth,
194 /// no namespace
195 NO_Namespace,
196 /// Insert fail
197 Insert,
198 /// Update fail
199 Update,
200 /// Query fail
201 Query,
202 /// Delete | Drop fail
203 Delete,
204 Other,
205}
206
207/// # Supper Exception
208/// It is the top-level implementation of all exceptions , you can get this from all more specific exceptions' recover param
209/// > Although it is the parent of all exceptions, it is actually the lowest level exception
210/// ## example
211/// ```rust
212/// use std::error::Error;
213/// use except_plugin::{SuperBuilder, SuperException, ExceptionFactory, Exceptions, SuperBuilderImpl, ExceptionLevel, Exception, DerefException};
214///
215/// pub fn test_super_exception() {
216/// // use ExceptionFactory -> get SuperBuilder -> build SuperException
217/// let e = ExceptionFactory::new::<SuperException, SuperBuilder>()
218/// .set_code(1006)
219/// .set_msg("super builder")
220/// .set_level(ExceptionLevel::Fatal)
221/// .build();
222/// dbg!(e);
223/// }
224///
225/// pub fn test_super_exception_result() -> Result<(), Box<dyn Error>> {
226/// // build a exception
227/// let mut e = ExceptionFactory::new::<SuperException, SuperBuilder>()
228/// .set_code(1006)
229/// .set_msg("super builder")
230/// .set_level(ExceptionLevel::Fatal)
231/// .build();
232/// e.set_msg("this is a super exception!");
233/// let e = e.deref_mut_exception();
234/// Err(Box::new(e))
235/// }
236/// fn main() {
237/// test_super_exception();
238/// let e = test_super_exception_result();
239/// match e {
240/// Ok(_) => {}
241/// Err(err) => {
242/// println!("{:?}", err.description());
243/// }
244/// }
245/// }
246/// ```
247#[derive(Debug, Clone, PartialEq)]
248pub struct SuperException {
249 code: u32,
250 msg: String,
251 level: ExceptionLevel,
252 timestamp: Duration,
253}
254
255
256impl NewFrom for SuperException {
257 type Builder = SuperBuilder;
258 fn new() -> Self::Builder {
259 SuperBuilder::new()
260 }
261 fn from_super(e: Box<dyn Exception>) -> Self where Self: Sized {
262 SuperException {
263 code: e.code(),
264 msg: String::from(e.msg()),
265 level: e.level(),
266 timestamp: e.timestamp(),
267 }
268 }
269}
270
271impl FromBuilder for SuperException {
272 type Output = SuperException;
273 type Input = SuperBuilder;
274 fn from_builder(builder: &Self::Input) -> Self::Output {
275 Self::Output {
276 code: builder.code(),
277 msg: String::from(builder.msg()),
278 level: builder.level(),
279 timestamp: builder.timestamp(),
280 }
281 }
282}
283//generate display and error for SuperException
284display_err_impl!(SuperException);
285
286exception_impl!(SuperException,Exceptions::Super);
287
288impl DerefException for SuperException {
289 fn deref_mut_exception(&mut self) -> Self {
290 SuperException {
291 code: self.code(),
292 msg: String::from(self.msg()),
293 level: self.level(),
294 timestamp: self.timestamp(),
295 }
296 }
297}
298
299impl Default for SuperException {
300 fn default() -> Self {
301 SuperException {
302 code: ExceptionCode::SUPER,
303 msg: String::from(SUPER_MSG),
304 level: ExceptionLevel::Info,
305 timestamp: SystemTime::now().duration_since(UNIX_EPOCH).unwrap(),
306 }
307 }
308}
309