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
use std::error::Error;
use std::fmt::{Debug, Display, Formatter};
pub struct ErrMsg {
msg: String,
}
impl Debug for ErrMsg {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
writeln!(f, "{}", self.msg.clone())
}
}
impl Display for ErrMsg {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
writeln!(f, "{}", self.msg.clone())
}
}
impl Error for ErrMsg {}
/// 不直接使用 `ErrMsgString`,其作为内部的参数使用
pub trait ErrMsgString {
fn new(msg: String) -> Self;
}
pub trait ErrMsgStr {
fn new(msg: &str) -> Self;
}
impl ErrMsgString for ErrMsg {
fn new(msg: String) -> Self {
ErrMsg { msg }
}
}
impl ErrMsgStr for ErrMsg {
fn new(msg: &str) -> Self {
ErrMsg {
msg: String::from(msg),
}
}
}
impl ErrMsg {
/// 抛出`String`异常消息
/// # Examples
///
/// 基本使用
///
/// ```
/// use uymas_cli::err::ErrMsg;
/// fn to_throw_err() -> Result<(), Box<dyn std::error::Error>>{
/// Err(ErrMsg::throw("参数缺少".to_string()))
/// }
/// ```
pub fn throw(msg: String) -> Box<dyn Error> {
Box::from(<ErrMsg as ErrMsgString>::new(msg))
}
/// 抛出`str`异常消息
/// # Examples
///
/// 基本使用
///
/// ```
/// use uymas_cli::err::ErrMsg;
/// fn to_throw_err() -> Result<(), Box<dyn std::error::Error>>{
/// Err(ErrMsg::throw_str("请求失败"))
/// }
/// ```
pub fn throw_str(msg: &str) -> Box<dyn Error> {
Box::from(<ErrMsg as ErrMsgString>::new(String::from(msg)))
}
}