代码之家  ›  专栏  ›  技术社区  ›  caprica

如何使用此错误转发带有泛型类型参数的错误

  •  0
  • caprica  · 技术社区  · 3 年前

    学习Rust,我正在使用 thiserror 板条箱包装一些例外情况。

    这是我想从中包装的例外 unrar 机箱:

    #[derive(PartialEq)]
    pub struct UnrarError<T> {
        pub code: Code,
        pub when: When,
        pub data: Option<T>,
    }
    

    我自己的代码是这样的:

    #[derive(Debug, Error)]
    pub enum MyError {
    
        #[error(transparent)]
        Io(#[from] io::Error),
    
        #[error(transparent)]
        Unrar(#[from] unrar::error::UnrarError), // <-- missing generics
    
        #[error("directory already exists")]
        DirectoryExists,
    }
    

    编译器抱怨上缺少泛型类型参数 UnrarError .

    所以我可以添加一个类型参数:

    #[derive(Debug, Error)]
    pub enum MyError<T> {
    
        #[error(transparent)]
        Io(#[from] io::Error),
    
        #[error(transparent)]
        Unrar(#[from] unrar::error::UnrarError<T>),
    
        #[error("directory already exists")]
        DirectoryExists,
    }
    

    但如果我这样做,现在我所有使用MyError的代码都需要关心这个类型参数,而实际上没有人关心这个参数。

    我应该如何习惯地处理这种情况?

    1 回复  |  直到 3 年前
        1
  •  3
  •   DenisKolodin    3 年前

    我建议您使用特定类型或添加自己的变体。这个 UnrarError 被设计为泛型,而不应该是泛型。

    请尝试以下操作:

    #[derive(Debug, Error)]
    pub enum MyError {
    
        #[error(transparent)]
        Io(#[from] io::Error),
    
        #[error(transparent)]
        Unrar(#[from] unrar::error::UnrarError<OpenArchive>),
    
        #[error(transparent)]
        UnrarProcessing(#[from] unrar::error::UnrarError<Vec<Entry>>),
    
        #[error("directory already exists")]
        DirectoryExists,
    }
    

    或者在这种情况下我更喜欢怎么做:

    #[derive(Debug, Error)]
    pub enum MyError {
    
        #[error(transparent)]
        Io(#[from] io::Error),
    
        #[error("unrar error")]
        Unrar,
    
        #[error("directory already exists")]
        DirectoryExists,
    }
    
    impl<T> From<unrar::error::UnrarError<T>> for MyError {
        fn from(err: unrar::error::UnrarError<T>) -> Self {
            // Get details from the error you want,
            // or even implement for both T variants.
            Self::Unrar
        }
    }
    
    推荐文章