shepmaster / snafu

Easily assign underlying errors into domain-specific errors while adding context
https://docs.rs/snafu/
Apache License 2.0
1.39k stars 60 forks source link

question: Best practice for automatic error conversion over two module levels? #437

Closed gabyx closed 6 months ago

gabyx commented 7 months ago

Is it possible to automagically convert between errors in different modules:

mod bottom {
    pub enum Bottom {
        A,
        B,
    }

    fn doit() -> Result<(), Bottom>
    {
       Err(Bottom::A)
    }

mod middle {
    #[derive(Debug, Snafu)]
    pub enum Middle {
        A,
        B,

        #[snafu(transparent)]
        Other {
            source: Bottom,
        },
    }

    fn doit() -> Result<(), Middle>
    {
       bottom::doit()?
    }
}

mod top {
    #[derive(Debug, Snafu)]
    pub enum Top {
        A,
        B,

        #[snafu(transparent)]
        Other {
            source: Middle,
        },
    }

    fn doit() -> Result<(), Top> {
      middle::doit()? // that should work with out a problem. --- (A)
      /// bottom::doit()? // that probably does not work without a `From` --- (B)
    }
}

So in (B) I would like to convert with ? automagically from Result<(), Bottom> to an error Result<(), Top>. Is there a best practice, I ve read it makes sense to define in each modules its own errors etc.