orion_error/traits/
owenance.rs

1use crate::{
2    core::{DomainReason, UvsNetFrom, UvsReason},
3    StructError, UvsDataFrom, UvsSysFrom, UvsTimeoutFrom,
4};
5
6/// 非结构错误(StructError) 转化为结构错误。
7///
8use std::fmt::Display;
9pub trait ErrorOwe<T, R>
10where
11    R: DomainReason,
12{
13    fn owe(self, reason: R) -> Result<T, StructError<R>>;
14    fn owe_logic(self) -> Result<T, StructError<R>>;
15    fn owe_biz(self) -> Result<T, StructError<R>>;
16    fn owe_rule(self) -> Result<T, StructError<R>>;
17    fn owe_validation(self) -> Result<T, StructError<R>>;
18    fn owe_data(self) -> Result<T, StructError<R>>;
19    fn owe_conf(self) -> Result<T, StructError<R>>;
20    fn owe_res(self) -> Result<T, StructError<R>>;
21    fn owe_net(self) -> Result<T, StructError<R>>;
22    fn owe_timeout(self) -> Result<T, StructError<R>>;
23    fn owe_sys(self) -> Result<T, StructError<R>>;
24}
25
26impl<T, E, R> ErrorOwe<T, R> for Result<T, E>
27where
28    E: Display,
29    R: DomainReason + From<UvsReason>,
30{
31    fn owe(self, reason: R) -> Result<T, StructError<R>> {
32        match self {
33            Ok(v) => Ok(v),
34            Err(e) => {
35                let msg = e.to_string();
36                Err(StructError::from(reason).with_detail(msg))
37            }
38        }
39    }
40
41    fn owe_logic(self) -> Result<T, StructError<R>> {
42        map_err_with(self, |msg| R::from(UvsReason::logic_error(msg)))
43    }
44    fn owe_biz(self) -> Result<T, StructError<R>> {
45        map_err_with(self, |msg| R::from(UvsReason::business_error(msg)))
46    }
47    fn owe_rule(self) -> Result<T, StructError<R>> {
48        map_err_with(self, |msg| R::from(UvsReason::rule_error(msg)))
49    }
50    fn owe_validation(self) -> Result<T, StructError<R>> {
51        map_err_with(self, |msg| R::from(UvsReason::validation_error(msg)))
52    }
53    fn owe_data(self) -> Result<T, StructError<R>> {
54        map_err_with(self, |msg| R::from_data(msg, None))
55    }
56    fn owe_conf(self) -> Result<T, StructError<R>> {
57        map_err_with(self, |msg| R::from(UvsReason::core_conf(msg)))
58    }
59    fn owe_res(self) -> Result<T, StructError<R>> {
60        map_err_with(self, |msg| R::from(UvsReason::resource_error(msg)))
61    }
62    fn owe_net(self) -> Result<T, StructError<R>> {
63        map_err_with(self, |msg| R::from_net(msg))
64    }
65    fn owe_timeout(self) -> Result<T, StructError<R>> {
66        map_err_with(self, |msg| R::from_timeout(msg))
67    }
68    fn owe_sys(self) -> Result<T, StructError<R>> {
69        map_err_with(self, |msg| R::from_sys(msg))
70    }
71}
72
73fn map_err_with<T, E, R, F>(result: Result<T, E>, f: F) -> Result<T, StructError<R>>
74where
75    E: Display,
76    R: DomainReason,
77    F: FnOnce(String) -> R,
78{
79    result.map_err(|e| {
80        let msg = e.to_string();
81        let reason = f(msg.clone());
82        StructError::from(reason).with_detail(msg)
83    })
84}