简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM