How to connect thiserror with anyhow?

Hi everyone.

In my app I have some user-defined error, like:

#[derive(Error, Debug)]
pub enum FieldError {
    #[error("Read error for field of type '{1}'")]
    CannotRead(#[source] std::io::Error, String),
    #[error("Invalid string when parse field of type ('{1}')")]
    InvalidString(#[source] std::string::FromUtf8Error, String),
    #[error("Write error for field of type '{1}'")]
    CannotWrite(#[source] std::io::Error, String),
}

and I want to use it with anyhow-result:

impl BinaryConverter for u8 {
    fn write_into(&mut self, buffer: &mut Vec<u8>) -> AnyResult<()> {
        buffer.write_u8(*self).map_err(|e| FieldError::CannotWrite(e, "u8".to_string()))
    }

    fn read_from<R: BufRead>(reader: &mut R, _: &mut Vec<u8>) -> Result<Self, FieldError> {
        reader.read_u8().map_err(|e| FieldError::CannotRead(e, "u8".to_string()))
    }

    fn to_bytes(&self) -> Vec<u8> {
        vec![*self]
    }
}

But I got an error:

expected `anyhow::Result<()>`, but found `Result<(), FieldError>`

Could somebody advice which trait can I implement to fix this ?

I think, I found. I can use .into():

buffer.write_u8(*self).map_err(|e| FieldError::CannotWrite(e, "u8".to_string()).into())

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.