Add a new trait to help return detailed JSON error message

This commit is contained in:
2022-09-20 14:06:34 +00:00
committed by GitHub
parent cbcd319aaf
commit bee6f4e4ba
6 changed files with 73 additions and 18 deletions

View File

@@ -1,3 +1,6 @@
#[cfg(feature = "server")]
use crate::server::result::JSONError;
/// Try with custom error message
pub trait TryErr2<T, E> {
/// try with custom error message
@@ -10,6 +13,15 @@ pub trait TryErr<T, E> {
fn try_err(self, err: E) -> Result<T, E>;
}
#[cfg(feature = "server")]
/// A quick way to return detailed JSON error
pub trait TryErr3<T> {
/// A quick way to return detailed JSON error
/// * `code` - error code
/// * `msg` - error message
fn try_err3<S: AsRef<str> + ?Sized>(self, code: i32, msg: &S) -> Result<T, JSONError>;
}
impl<T: ToOwned + ToOwned<Owned = T>, E> TryErr2<T, E> for Option<T> {
fn try_err2(&self, v: E) -> Result<T, E> {
match self {
@@ -46,3 +58,20 @@ impl<E> TryErr<(), E> for bool {
}
}
}
#[cfg(feature = "server")]
impl<T, E> TryErr3<T> for Result<T, E>
where
E: std::fmt::Debug + std::fmt::Display,
{
fn try_err3<S: AsRef<str> + ?Sized>(self, code: i32, msg: &S) -> Result<T, JSONError> {
match self {
Ok(v) => Ok(v),
Err(e) => Err(JSONError::from((
code,
format!("{} {}", msg.as_ref(), e),
format!("{:?}", e),
))),
}
}
}