Use enum variant as error source?
houqp opened this issue · comments
QP Hou commented
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?
David Tolnay commented
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.
QP Hou commented
Thanks for the quick reply! I will stick to manual From
impl for now :)