dtolnay / thiserror

derive(Error) for struct and enum error types

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Use enum variant as error source?

houqp opened this issue · comments

I have a use-case where I need to map a enum variant based on variants from another enum. For example, I want to wrap ErrorBar::E1 as ErrorOutter::E1 and all other ErrorBar variants to ErrorOutter::Unknown:

enum ErrorOutter {
    E1 {
        #[from]
        source: ErrorBar::E1
    }
    Unknown {
        #[from]
        source: ErrorBar
    }
}

Is this something that could be supported by thiserror?

For anything more complicated than what is handled by the current #[from] attribute, I would recommend handwriting the From impl yourself. In this case:

impl From<ErrorBar> for ErrorOuter {
    fn from(source: ErrorBar) -> Self {
        match source {
            ErrorBar::E1(_) => ErrorOuter::E1 { source },
            _ => ErrorOuter::Unknown { source },
        }
    }
}

If this comes up super commonly in your codebase, try checking if there is a derive(From) library that handles your use case.

Thanks for the quick reply! I will stick to manual From impl for now :)