When errors implement From
, propagation of errors is very easy and terse:
do_this(arg1)?.do_that(arg2)?;
However, the From
impl is context-free, and some errors aren't informative on their own (the io::Error
without a filename!)
anyhow
helps here by having a .context()
method, but that works only for anyhow
's own error type. For libraries using specific enum Error
(thiserror
-style) this isn't as neat:
do_this(arg1).map_err(|e| Error::new(e, arg1))?.do_that(b).map_err(|e| Error::new(e, arg2))?;
And something like .context()
would require extra traits and bespoke implementations.
I wonder if the standard library could provide some universal helper method to cut down on the syntactic noise of map_err(|_|)
.
For example, there's option.zip(new_val)
that makes Some((previous, new_val))
. What if Result
had .zip
? It would be possible to implement From<(Error, Context)> for CustomError
, even by boilerplate-generating libraries, so code like this could work:
do_this(arg1).zip(arg1)?.do_that(b).zip(arg2)?;
For example imagine impl From<(io::Error, PathBuf)> for ErrorWithPath
+ zip
:
fs::File::open(&path).zip(path)?
zip
is not the best name for it, but maybe a better-named similar pattern is possible?