urlyy commented on issue #2706:
URL: https://github.com/apache/fory/issues/2706#issuecomment-3393109344

   btw, this is a small suggestion I have for refactoring `error.rs`. This kind 
of refactoring can reduce the usage of `anyhow` in the code, and using 
`crate::error::Error` and `crate::{bail, ensure}` instead of an external 
library feels more conformable.
   
   ```rust
   use std::borrow::Cow;
   
   use thiserror::Error;
   
   #[derive(Error, Debug)]
   #[non_exhaustive]
   pub enum Error {
       // not use this, just as a example.
       // You can create new error enums for specific cases in the future.
       #[error("Fory on Rust not support Ref type")]
       Ref,
   
       // don't use this directly, use Error::from() instead
       #[error(transparent)]
       Wrapped(#[from] anyhow::Error),
   
       // don't use this directly, use Error::msg(str or String) instead
       #[error("{0}")]
       Msg(Cow<'static, str>),
   }
   
   impl Error {
       pub fn msg<S: Into<Cow<'static, str>>>(s: S) -> Self {
           Error::Msg(s.into())
       }
   }
   
   #[macro_export]
   macro_rules! ensure {
       ($cond:expr, $msg:literal) => {
           if !$cond {
               return Err($crate::error::Error::msg($msg));
           }
       };
       ($cond:expr, $err:expr) => {
           if !$cond {
               return Err($crate::error::Error::Wrapped($err));
           }
       };
       ($cond:expr, $fmt:expr, $($arg:tt)*) => {
           if !$cond {
               return Err($crate::error::Error::msg(format!($fmt, $($arg)*)));
           }
       };
   }
   
   #[macro_export]
   macro_rules! bail {
       ($err:expr) => {
           return Err($crate::error::Error::msg($err))
       };
       ($fmt:expr, $($arg:tt)*) => {
           return Err($crate::error::Error::msg(format!($fmt, $($arg)*)))
       };
   }
   ```
   
   
   you can:
   ```rust
   use fory_core::error::Error;
   
   Error::msg(format!(
       "TypeId {:?} not found in type_info_map, maybe you forgot to register 
some types",
       type_id
   ))
   
   Error::msg("named_ext type must be registered in both peers")
   
   Error::from(other_error)
   
   Error::Ref
   ```
   
   The usage of `bail!` and `ensure!` is the same as `anyhow::{bail, ensure}`.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to