#Need help implementing FromResidual trait to a custom enum Error

29 messages · Page 1 of 1 (latest)

void fossil
#

i have this custom enum trait rs pub enum FileError { FileNotFound, EmptyFile, InvalidFile, UnsupportedExt, } i'm using calamine to read excel sheets, rn i'm trying to use the question mark operator to convert the error to my custom error, the thing is i couldn't find any way to implement the FromResidual trait, i can't even import it from std::ops::FromResidual , Note that open_workbook() return a Result<R, R::Error> where R: Reader<BufReader<File>>, P: AsRef<Path>, any idea on how to implement the FromResidual trait

mortal bramble
#

Something like this

#

@void fossil

#

?play

pub enum FileError {
    NotFound,
    PermissionDenied,
    Unknown,
}

struct OtherError;

fn residual() -> Result<(), OtherError> {
    Err(OtherError)
}

impl From<OtherError> for FileError {
    fn from(_: OtherError) -> Self {
        FileError::Unknown
    }
}

fn open_file() -> Result<(), FileError> {
    residual()?;
    Ok(())
}

fn main() {
    open_file().unwrap_or(());
}
ebon groveBOT
mortal bramble
void fossil
#

!paste

mortal bramble
#

-paste

#

intersting

void fossil
mortal bramble
#

one se

#

c

void fossil
#

alr

mortal bramble
#

You need to implement From<R::Error> for your custom error

void fossil
lone pasture
#

each type of Reader you use has a specific error type

#

you need to write a impl From<ThatParticularError> for FileError for each specific such error type that you might encounter, just like the impl From<...> for FileError that you have already written

#

(FromResidual is a red herring; that would be relevant only if you were writing a new type like Result but different.)

mortal bramble
#


impl From<XlsError> for FileError {
    fn from(_: XlsError) -> Self {
        FileError::InvalidFile
    }
}
impl From<calamine::XlsxError> for FileError {
    fn from(_: calamine::XlsxError) -> Self {
        FileError::InvalidFile
    }
}
impl From<io::Error> for FileError {
    fn from(value: io::Error) -> Self {
        FileError::FileNotFound
    }
}

impl From<csv::Error> for FileError {
    fn from(_: csv::Error) -> Self {
        FileError::InvalidFile
    }
}

impl From<serde_json::Error> for FileError {
    fn from(_: serde_json::Error) -> Self {
        FileError::InvalidFile
    }
}

impl From<calamine::DeError> for FileError {
    fn from(_: calamine::DeError) -> Self {
        FileError::InvalidFile
    }
}
#

There you go

#

these should be sufficient

void fossil
void fossil
mortal bramble
#

If not, suite yourself

void fossil