How to implement Error :: cast correctly?

I have a problem with implementing a tag Error. I want to wrap an error from Diesel or another database driver. I have not even come close to implementation From, since I am no longer doing it Error. The line that causes the code to not compile is the one that is at the very end of the code block.

use std::fmt;
use std::error::{self, Error};

#[derive(Debug)]
pub enum MyError {
    NotFound(String),
    PersistenceError(Box<Error + Send + Sync>),
}

pub type MyResult<T> = Result<T, MyError>;

impl fmt::Display for MyError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            MyError::NotFound(ref msg) => write!(f, "Not found: {}", msg),
            MyError::PersistenceError(ref cause) => write!(f, "Persistence error: {}", cause),
        }
    }
}

impl Error for MyError {
    fn description(&self) -> &str {
        match *self {
            MyError::NotFound(ref msg) => msg,
            MyError::PersistenceError(ref cause) => cause.description(),
        }
    }

    fn cause(&self) -> Option<&Error> {
        match *self {
            MyError::NotFound(_) => None,
            // `*cause` does not live long enough
            MyError::PersistenceError(cause) => Some(&*cause),
        }
    }
}

I also tried:

* The reason is short-lived.

MyError::PersistenceError(cause) => Some(&*cause),

main core :: marker :: Size not implemented for type std :: error :: Error + Send + Sync + 'static [E0277]

MyError::PersistenceError(ref cause) => Some(cause),

trat std :: error :: Error not used for type `& Box

MyError::PersistenceError(ref cause) => Some(&cause)

But none of them worked.

+4
source share
1 answer

:

match *self {
    MyError::NotFound(_) => None,
    MyError::PersistenceError(ref cause) => {
        let () = cause;
    },
}

, cause &Box<std::error::Error + Send + Sync>.

, Box<std::error::Error + Send + Sync>, , std::error::Error + Send + Sync ( ). , &Error:

match *self {
    MyError::NotFound(_) => None,
    MyError::PersistenceError(ref cause) => Some(&**cause),
}
+6

All Articles