HiDefender
HiDefender

Reputation: 2378

Does Rust have hooks for early return on errors?

panic! allows the setting of a custom (albeit global) hook. Is there anything comparable for early returns with the ? operator? I have a function that needs to close some resources in a special way before exiting. I could write a function ok_or_close() that closes the resources before returning the error:

fn opens_resources() -> Result<(), MyError> {
    //Opens some stuff.

    //Now a bunch of functions that might raise errors.
    ok_or_close(foo(), local variables)?;
    ok_or_close(bar(), local variables)?;
    ok_or_close(baz(), local variables)?;

    ok_or_close(Ok(()), local variables)
}

But that seems verbose. What I'd really like to do is this:

fn opens_resources() -> Result<(), MyError> {
    //Opens some stuff.

    //Now a bunch of functions that might raise errors.
    foo()?;
    bar()?;
    baz()?;

on_err:
    //Closes some stuff. Would prefer not to make
    //  this a function, uses many local variables.
    Ok(())
}

Is there a way to do this or a pattern of programming that gets around this?

Upvotes: 0

Views: 215

Answers (1)

richerarc
richerarc

Reputation: 250

The closest thing to this would be the Try trait which allows you to implement how ? affect a specific type, but sadly it is still a nightly experiment as stated here

If you're interested in this features I'd recommend you give a +1 at this issue

Upvotes: 2

Related Questions