rust-lang-deprecated / failure

Error management

Home Page:https://rust-lang-nursery.github.io/failure/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Match a concrete type issue

alexandrvoronsky opened this issue · comments

Hello guys!

I am trying to use failure, but have some issues (except my rustasian newbie skills). It would be great if you will help me to understand how to resolve them.
So, I have defined my error using enum:

#[derive(Debug, Fail)]
pub enum MyErrorType {
    #[fail(display = "Thing is not found")]
    NotFound,
    #[fail(display = "Unknown error")]
    Unknown,
}

The next thing what I am going to do is to throw an Error:

fn throw() -> Result<(), Error> {
    Err(MyErrorType::NotFound.into())
}

And the problem that is not clear to me at all - how to catch the actual type:

let res = match throw() {
                Ok(()) => "ok",
                Err(err) => {
                    match err {
                        MyErrorType::NotFound => "1",
                        MyErrorType::Unknown => "2"
                    }
                }
            }

How to properly deal with it?

BTW if to use separate structs instead of enum it will be working. I mean smth like this:

#[derive(Debug, Fail)]
#[fail(display = "Error Unknown")]
pub struct MyErrorTypeUnknown

#[derive(Debug, Fail)]
#[fail(display = "ErrorNotFound")]
pub struct MyErrorTypeNotFound

let res = match throw() {
                Ok(()) => "ok",
                Err(err) => {
                    match err {
                        MyErrorTypeNotFound => "1",
                        MyErrorTypeUnknown=> "2"
                    }
                }
            }

Thanks!

Take a look at failure::Error.downcast_ref<T>() which can be used something like the following, based on your original example:

            let res = match throw() {
                Ok(()) => "ok",
                Err(err) => {
                    if let Some(my_err) = err.downcast_ref::<MyErrorType>() {
                        match my_err {
                            MyErrorType::NotFound => "1",
                            MyErrorType::Unknown => "2"
                        }
                    }
                    // handle other types
                }
            }

@dekellum I see this function in sources of failure::Error, but it's not accessible, can't realize why

Works for me. Is the Error type of your throw() function actually failure::Error or is it std::error::Error or some other?

Yes, it is failure::Error.

Tried to build and it works this way.
But the last mystery thing I don't why nor RLS nor Intellij won't highlight it and index as a function. It could be resolved by myself if I knew that syntax highlighter is not working properly. =)

Thanks you very much!