rust

In Rust what is the idiomatic way to run a side effect (such as logging) if Result is Err


From a Result, I would like to run a side effect on it if it's an Err (like logging the error) and return the error, what's the most idiomatic to do it?

I could do this:

fn do_something() -> Result<(), MyError> {...}

fn foo() -> Result<(), MyError> {
  do_something()
    .map_err(|err| { 
      println!("Got error in Foo: {:#?}", err);
      err
    })?;
  ...
}

But I am not a big fan of this, as this feels like a misuse of map_xxx: I am doing a side-effect on a map... function, and I am not even mapping the error to something else.

I guess this would make the side effect more obvious:

let result =  do_something();
if let Err(err) = result {
  println!("Got error in Foo: {:#?}", err);
  return Err(err);
}
...

But I find it verbose. Ideally I would be looking to something like

do_something()
  .if_err(|err| {println!("Got error in Foo: {:#?}", err);})?;

Solution

  • Since Rust 1.76.0, the inspect_err method can be used.

    do_something().inspect_err(|err| println!("Got error in Foo: {err:#?}"))?;