How to map all errors in a scope?

I'm trying to map all errors inside a scope, like:

let result: Result<(), u32> = {
    function_that_errors_with_u32()?;
    another_function_that_errors_with_u32()?;
};
result.map_err(|_| "I need a string though!")?;

However, when using ? inside a scope it tries to return errors in the parent scope, so it fails saying that there's no way to convert a u32 to a &str (I'm not sure if this would be the case, in my actual code I use different types). Is there a way to use ? in a way that it throws the error inside the scope and not outside?

Eventually we may have try {} blocks for this, but you can sometimes fake that with a closure:

let result: Result<(), u32> = (|| {
    function_that_errors_with_u32()?;
    another_function_that_errors_with_u32()
})();

Note that I left off the second ?, otherwise you'd have to end with Ok(()).

There are three ways to do this,

  1. Use an immediately invoked closure
let result: Result<(), u32> = (|| {
    function_that_errors_with_u32()?;
    another_function_that_errors_with_u32()?;
})();
result.map_err(|_| "I need a string though!")?;
  1. Use the Result combinators
let result: Result<(), u32> = function_that_errors_with_u32()
    .and_then(|_| another_function_that_errors_with_u32());
result.map_err(|_| "I need a string though!")?;
  1. Use the nightly feature for try blocks
let result: Result<(), u32> = try {
    function_that_errors_with_u32()?;
    another_function_that_errors_with_u32()?;
};
result.map_err(|_| "I need a string though!")?;

Thank you both @cuviper and @RustyYato! I set Krishna's answer as the solution as it provides more options. Can't wait for try {} blocks to be a thing <3

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.