How to convert all panic into Result and return it

Hello
I have this code:

    fn run(args: String)-> Result<Output, String> {
        let mut sh = Command::new("/usr/bin/shqwqw");

        let mut child = sh
            .args(["-c","cat"])
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .spawn()
            .or(Err("can not execute shell"))?;
        
        let mut stdin = child.stdin.take().expect("can not connect to stdin");
            std::thread::spawn(move || {
                stdin.write_all(args.as_bytes()).expect("err write to stdin");
            });
        let output = child.wait_with_output().expect("err waiting to finish");
        
        Ok(output)
    }

As you can see it return Result
The idea is to convert all panic into meaningful errors and return them as Err("...").
I managed to fix the first one, but I do not understand how to change the rest of expects.
This function must return value or an error.
If my approach was not correct then suggest anything different.

Thank you in advance.

I found how: just use match for all Result and Option

{
    Ok(v) => v,
    Err(_) => return Err("error message".to_string()),
};
{
    Some(v) => v,
    None    => return Err("error message".to_string()),
};

No panic no issue.

The ? operator (called try) is used to return errors from functions without writing full match every time.

.map_err method allows customizing the error before returning it.

1 Like

Thank you
I will try it.