What is the most idiomatic way to merge two error types?

前端 未结 2 710
暖寄归人
暖寄归人 2020-12-21 08:41

I have a type Foo whose methods may "raise" errors of an associated type Foo::Err.

pub trait Foo {
    type Err;
    
             


        
相关标签:
2条回答
  • 2020-12-21 08:55

    You should use a trait object Error, and you return the first error that you encounter:

    pub trait Bar {
        fn bar<F: Foo>(&mut self, foo: F) -> Result<F, Box<dyn Error>>;
    }
    

    or implement your trait like this:

    impl Bar for MyType {
        type Err = Box<dyn Error>;
    
        fn bar<F: Foo>(&mut self, foo: F) -> Result<F, Self::Err>;
    }
    

    If you really want to have your two errors (but this is strange because one error suffices to make the process not ok), you can use a crate like failure to create an "error trace".

    As a general advice, you should not forget to use the traits from std to add more semantic to your code.

    0 讨论(0)
  • 2020-12-21 09:05

    Typically you don't do a "merge", but instead use nested errors, like this.

    enum IntError {
        Overflow,
        Underflow
    }
    
    enum StrError {
        TooLong,
        TooShort,
    }
    
    enum GenericError {
        Int(IntError),
        Str(StrError),
    }
    
    impl From<IntError> for GenericError {
        fn from(e: IntError) -> Self {
            GenericError::Int(e)
        }
    }
    
    impl From<StrError> for GenericError {
        fn from(e: StrError) -> Self {
            GenericError::Str(e)
        }
    }
    
    0 讨论(0)
提交回复
热议问题