Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FromStr derive could support setting the error type #91

Open
Ten0 opened this issue Apr 20, 2020 · 1 comment
Open

FromStr derive could support setting the error type #91

Ten0 opened this issue Apr 20, 2020 · 1 comment

Comments

@Ten0
Copy link
Contributor

Ten0 commented Apr 20, 2020

When you derive on an enum, sometimes you want to implement some From<XXXNotFound> for some other error types, with maybe more explicit messages. It would be great if we could have an attribute that enables us to set the function that would be used to build the error from the original &str.

e.g.

#[derive(EnumString)]
#[strum(parse_err_ty = "SomeEnumNotFound", parse_err_fn = "some_enum_not_found_err")]
pub enum SomeEnum {
	A,
	B,
}

pub struct SomeEnumNotFound;
fn some_enum_not_found_err(_not_found: &str) -> SomeEnumNotFound { SomeEnumNotFound }

generating

impl FromStr for SomeEnum {
    type Err = SomeEnumNotFound;
    fn from_str(s: &str) -> Result<SomeEnum, Self::Err> {
        match s {
            "A" => A,
            "B" => B,
            other => some_enum_not_found_err(other),
        }
    }
}

If parse_err_fn is not specified but parse_err_ty is, we could fallback on From<strum::ParseError>.

@Ten0 Ten0 changed the title FromStr derive could support setting the error kind FromStr derive could support setting the error type Apr 20, 2020
@dragonnn
Copy link

dragonnn commented Sep 15, 2020

This would be so nice! I am parsing a big XML with Rust and many fields are implemented as Enum, it uses strong-xml crate and well, returning FromStr(VariantNotFound) isn't really helpful when I have already five different enums and need to know with one did failed when parsing it from String.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants