derive_more icon indicating copy to clipboard operation
derive_more copied to clipboard

derive(FromStr): Support for mapping error to custom error type

Open Boscop opened this issue 5 years ago • 2 comments
trafficstars

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? :)

Boscop avatar Jan 07 '20 12:01 Boscop

Can you show a bit more usage of this FromStr implementation? And also the definition of the MyError type.

JelteF avatar Jan 07 '20 12:01 JelteF

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())))]

JelteF avatar Dec 22 '23 00:12 JelteF