How to avoid "panic " output in linux when this panic has been catch?

the code looks like below:

let x_handle: tokio::task::JoinHandle<Result<Result<Vec<serde_json::Value>, Box<dyn Error + Send + Sync>>, Box<dyn Error + Send + Sync>>> = tokio::spawn(async {
            let x = a_async_function(s2i_clone, fh_clone, st_clone).await;
            Ok(x)
        });
        match x_handle.await {
            Ok(kd) => {
                match kd.unwrap() {
                    Ok(kd) => {
                        if kd.len() < 1 {
                            println!("no data");
                        } else {
                            assert!(kd.len() == 1, "the number must be 1.");
                            let x = another_function(&kd);
                            println!(x);
                        }
                    },
                    Err(_) => println!("catched panic");
                }
            },
            Err(_) => println!("catched panic");
        }        

when I run this code, the "panic" occurs and has been catched, but I still find 'panic' in '/var/spool/mail/..' which looks like as "thread 'tokio-runtime-worker' panicked at 'called Option::unwrap() on a None value'"; so shall I avoid this panic record in '/var/spool/mail/..'?

Maybe you can catch the panic before tokio does with this: FutureExt in futures::future - Rust

You may need to wrap your future in AssertUnwindSafe in std::panic - Rust if catch_unwind complains.

Err(_) does not catch panics from .unwrap(). You must stop using .unwrap() if you don't want this function to panic. Otherwise .unwrap() will continue to throw panics, even if you use it inside match.

unwrap() is just panic-throwing function no matter what you do, and you should avoid using it. Rust uses ?, if let, and match on non-unwrapped values for error handling that doesn't panic.

7 Likes

thanks, got it.