How to get process exit/error message?

We can get process exit code through process::Command::Output::ExitStatus, but how to get the exit message?

For example,

curl bad.domain
curl: (6) Could not resolve host: ...

Is there an API can get "Could not resolve host:" detail message...

There is no such thing as an "exit message". What you are describing is whatever the process prints to the standard output and/or the standard error.

But the standard error is always empty from the example above. The problem is how to get error content.

Cannot reproduce.

It's not clear what you mean here. If you see output from a program when it's run, that means that it wrote that to either stdout or stderr. When you run a program in Rust using, eg the Command::status() method, Rust tells the operating system to use the same stdin, stdout and stderr (collectively, stdio) as the calling program, so you as the user running this parent Rust program see the messages of the child program.

If you instead use Command::output() as linked above, Rust tells the operating system to give it the stdout and stderr output, and it collects them into two Vec<u8> values on the result so you can do something with them.

If you want them as a string, you'll have to convert them, possibly with String in std::string - Rust (note there's no guarantee that any random program output is UTF-8, and on Windows it's sometimes UTF-16)

From there, you can probably figure out how to chop up the lines to get the message out - the string methods are pretty helpful.

2 Likes

Hmm, maybe I know the problem. I prevent the curl output by put -s --silent command option; so the error content being wiped out, but error code left in ExitStatus.

Well if you actively suppress output, then it's not surprising that it's not there.

As I implied in my reply, if you use output(), then the user won't see that output.

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.