derive_more
derive_more copied to clipboard
derive(FromStr): Support for mapping error to custom error type
We have a lot of instances of this pattern:
#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy, DieselNewType, Serialize, Deserialize, From, Into, Display)]
pub struct Foo(Uuid);
impl FromStr for Foo {
type Err = MyError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(
Foo(
s.parse()
.map_err(|err| MyError::InvalidFoo(err, Backtrace::new()))?
)
)
}
}
We currently can't use derive(FromStr) to reduce this boilerplate but it would be nice if support for wrapping the error using a custom function could be added.
E.g.
#[derive(FromStr)]
#[from_str = |err| MyError::InvalidFoo(err, Backtrace::new())]
struct Foo(Uuid);
Or similar.. Would that be possible? :)
Can you show a bit more usage of this FromStr implementation? And also the definition of the MyError type.
After reading it again, I do get this request now. I think it makes sense for FromStr to be able to map the original error type to another. I'd be open to accepting a PR for this. Probably with sligtly different attribute syntax though, something like this would fit better with the design of the existing attributes:
#[from_str(map_err(|err| MyError::InvalidFoo(err, Backtrace::new())))]