rust-lang-deprecated / failure

Error management

Home Page:https://rust-lang-nursery.github.io/failure/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Wrapping in `Context` as attribute

vorner opened this issue · comments

Hello

I'm not sure if I'm using the .context and with_context things as expected, but I'm trying to build detailed context „chains“ (and print all the levels when logging). However, sometimes doing that requires to jumping through ugly loops like this:

fn do_something(xy: &str) -> Result<Whatever, Error> {
  let inner = || {
    first_part()?;
    second_part()?;
    third_part(xy)?;
  };
  Ok(inner().with_context(|_| format!("Failed to do something about {}", xy)?))
}

So I wonder, now we have the attribute style procedural macros, if it would be possible to do this kind of thing using a decorator like this:

#[failure(with_context = "Failed to do something about {}", xy)]
fn do_something(xy: &str) -> Result<Whatever, Error> {
    first_part()?;
    second_part()?;
    third_part(xy)?;
}

And possibly make it work on try blocks too.

Anyway, this is a very much rough and unformed idea.

This seems hard since xy might not be available at the time the error occurs (if it's something non-copy, it could have been moved). Formatting at the start of the function would avoid this but would be unfortunate.

I guess it would be acceptable if the macro-generated code simply failed to compile in the non-copy case. After all, such problem exists with manual contexting as well and the case of the parameter being a reference or a copy type is reasonably common to be of some help even with the limitation.