Heinemann
Heinemann

Reputation: 45

Is it possible to return one String if the function call is in an panic::catch_unwind in rust?

My code:

let result= panic::catch_unwind( || {
   do_olr(
      &payload_buffer[..],
      args.cmd_collect
   );
});

if !result.is_ok() {
    error!("Premature end of payload$")
}

I would like to keep the catch_unwind for safety reasons but still return a value. so that there is something like this:

let val = do_olr(
   &payload_buffer[..],
   args.cmd_collect
);

is that possible?

Upvotes: 0

Views: 193

Answers (1)

mcarton
mcarton

Reputation: 29981

std::panic::catch_unwind returns whatever the closure returned in case it didn't panic:

fn main() {
    let result = std::panic::catch_unwind(|| {
        println!("hello!");

        42
    });
    println!("{:?}", result);

    let result = std::panic::catch_unwind(|| {
        panic!("oh no!");
    });
    println!("{:?}", result);
}

(Permalink to the playground)

This prints

hello!
Ok(42)
Err(Any)

I would like to keep the catch_unwind for safety reasons

I don't really see how catch_unwind helps with safety: If you are executing unknown code, it could terminate your program in ways not catchable with catch_unwind even in safe code. There is absolutely no guarantee that catch_unwind will be called. catch_unwind provides no isolation whatsoever.

Upvotes: 1

Related Questions