How to make this code work?
- SocketAddr::from_str("")?;
+ SocketAddr::from_str("").map_err(ParseError::from)?;
I know map err would fix this, any other methods to fix it more elegantly?
I don't see a way to make the thiserror
macro do it for you offhand, but you can write a From
implementation. It may not be ideal if there's more than one path from some source error type to your target nested type.
Tracking Issue for try_trait_v2
, A new design for the ?
desugaring (RFC#3058) · Issue #84277 · rust-lang/rust (github.com)
If this is stable, it can call the try chain and can be automatically convert to MyError?
I'm not sure exactly what you mean, but ?
is using that new design already.
I mean would it able to convert error chainly in the future? e.g. my example code can be compiled.
That's not possible in general, because how is the macro supposed to know how many layers of From
to go through?
By the way, it would be really bad design, too, for the exact same reason: the reader of the code doesn't know the path either, just by looking at the context of the error. It would require knowing about all intermediate impls, ie. global analysis, which is also hard for humans. If you want two levels of conversions, just write out the map_err()
. It's not much effort.
Besides the ways already demonstrated?
I doubt it. You have a known starting point and a known ending point, but inbetween you're calling through a generic. The compiler would have to take every impl From<AddrParseError> for X
, and for each one of those every From<X> for MyError
. And that's just for two levels, naturally it combinatorially explodes for more levels.
After it did all that checking, it could only succeed if there was a unique solution.
There's always a conflict if you don't check for a unique solution after each new level.
This search for some unique shortest translation isn't something that could be represented by a trait, and whether it's the current implementation or another, people do want ?
to be based on a trait and not some magical compiler-only thing.
If there's only one sensible path from your starting error to your ending error, and you're sure that won't change, just write the From
implementation.