#[allow(unused_imports)]
pub use anyhow::{Context, Result, anyhow, bail}; use std::fmt::Display;
#[macro_export]
macro_rules! err {
() => {
anyhow!("{:?} ", (file!(), line!()))
};
($err:ident) => {
anyhow!("{:?} {}", (file!(), line!()), anyhow!($err).chain().map(|e| e.to_string()).collect::<String>())
};
($msg:literal) => {
anyhow!("{:?} {}", (file!(), line!()), $msg)
};
($fmt:literal, $($args:tt)*) => {
anyhow!("{:?} {}", (file!(), line!()), format!($fmt, $($args)*))
};
($err:ident, $($args:tt)*) => {
anyhow!("{:?} {} {}", (file!(), line!()), format!($($args)*), anyhow!($err).chain().map(|e| e.to_string()).collect::<String>())
};
($err:expr) => {
anyhow!("{:?}", $err)
};
}
pub trait Cauz<C, T> {
#[allow(dead_code)] fn cauz(self, cause: C) -> Result<T>; }
impl<C, T, E> Cauz<C, T> for core::result::Result<T, E>
where
C: Display + Send + Sync + 'static,
E: Into<anyhow::Error>,
{
#[inline(always)]
fn cauz(self, cause: C) -> Result<T> {
(self.map_err(|e| (e.into() as anyhow::Error)) as anyhow::Result<_>).with_context(|| cause)
}
}
impl<C, T> Cauz<C, T> for Option<T>
where
C: Display + Send + Sync + 'static,
{
#[inline(always)]
fn cauz(self, cause: C) -> Result<T> {
self.with_context(|| cause)
}
}
impl<C> Cauz<C, ()> for bool
where
C: Display + Send + Sync + 'static,
{
#[inline(always)]
fn cauz(self, cause: C) -> Result<()> {
self.then_some(()).with_context(|| cause)
}
}
#[cfg(feature = "cauz_tonic")]
pub use cauz_tonic::*;
#[cfg(feature = "cauz_tonic")]
mod cauz_tonic {
use super::*;
use std::fmt::Debug;
use tonic::Status;
pub trait CauzTonic<C, T> {
#[allow(dead_code)] fn cauz2(self, cause: C) -> Result<T, Status>; }
impl<C, T, E> CauzTonic<C, T> for core::result::Result<T, E>
where
C: Display + Send + Sync + 'static,
E: Into<anyhow::Error>,
{
#[inline(always)]
fn cauz2(self, cause: C) -> Result<T, Status> {
(self.map_err(|e| (e.into() as anyhow::Error)) as anyhow::Result<_>)
.with_context(|| cause)
.map_err(|e| Status::internal(e.chain().map(|e| e.to_string()).collect::<String>()))
.inspect_err(|e| log::error!("{}", e.message()))
}
}
impl<C, T> CauzTonic<C, T> for Option<T>
where
C: Display + Send + Sync + 'static + Debug,
{
#[inline(always)]
fn cauz2(self, cause: C) -> Result<T, Status> {
self.ok_or_else(|| Status::internal(cause.to_string()))
}
}
impl<C> CauzTonic<C, ()> for bool
where
C: Display + Send + Sync + 'static + Debug,
{
#[inline(always)]
fn cauz2(self, cause: C) -> Result<(), Status> {
self.then_some(()).ok_or_else(|| Status::internal(cause.to_string()))
}
}
}