How to get the error why a process fails to spawn?

Using the std::process::Command's .spawn() method, I get a Result with an error when it fails.

But how do I get the error code of why it failed?

I just getting an error struct. When I print, it contains the information I need (like the error code, a descriptive message, kind), but I can't get it in the code. Of course, parsing the string of an error that may totally change just to get the error code is absolutely stupid, error-prone, fragile, and a non-go.

But I can't find how to get the error code. How to do it?

The spawn method from std::process::Command returns a Result<Child, std::io::Error>. You can get the ErrorKind enum like this:

match Command::new("ls").spawn() {
  Ok(output) => // Do something with the output
  Err(error) => match error.kind() {
    // Here you'll match the variants from https://doc.rust-lang.org/std/io/enum.ErrorKind.html
  }
}
2 Likes

Thanks! That's exactly what I need.

I think I should improve a lot my skills in reading the rust documentation. Sometimes it can be a little dry, but usually, the answer is there and I fail to see it.

I agree that it can take some time to get used to Rust's documentation. If you have any observations / ideas on how to improve any section in particular (i.e. how to make it easier for users to find how to match the specific error from std::io::Error), I think they would be very welcomed.

At the same time, IMHO the Rust documentation is by far the best one I have seen / used in my career. I can easily navigate docs from a specific crate to the standard library and go back and forth until I get the whole picture of how to work with it. The experience is much better than traditional isolated documentation sites for each one of my dependencies.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.