英文:
Ok() is handling error message instead of Err() in match expression
问题
我执行命令:
use std::process::Command;
pub fn search(query: &str, flag: &str) -> Vec<String> {
let command = format!("xdotool search --onlyvisible {} {}", flag, query);
let output = Command::new("sh").arg("-c").arg(command).output();
match output {
Ok(o) => {
println!("Success message: {:?}", o);
String::from_utf8_lossy(&o.stdout)
.lines()
.map(|s| s.to_owned())
.collect()
}
Err(err) => {
eprintln!(
"Error message: {:?}",
String::from_utf8_lossy(&err.to_string().as_bytes())
.trim()
.to_owned()
);
Vec::new()
}
}
}
如果我使用错误的 flag
,我会得到一个错误消息,但它被处理为 search()
函数中的 Ok()
。为什么会这样?如何让 Err()
处理错误消息呢?
英文:
I execute commands:
use std::process::Command;
pub fn search(query: &str, flag: &str) -> Vec<String> {
let command = format!("xdotool search --onlyvisible {} {}", flag, query);
let output = Command::new("sh").arg("-c").arg(command).output();
match output {
Ok(o) => {
println!("Success message: {:?}", o);
String::from_utf8_lossy(&o.stdout)
.lines()
.map(|s| s.to_owned())
.collect()
}
Err(err) => {
eprintln!(
"Error message: {:?}",
String::from_utf8_lossy(&err.to_string().as_bytes())
.trim()
.to_owned()
);
Vec::new()
}
}
}
If I use a wrong flag
, I get an error message, but it's being handled of Ok()
in the search()
function:
Success message: Output { status: ExitStatus(unix_wait_status(256)), stdout: "", stderr: "search: unrecognized ...
Why is this? And how to make Err()
handle the error message instead?
答案1
得分: 7
output()
返回的 Err
表示生成进程失败。 这与进程本身的成功/失败无关。 您需要检查 ExitStatus
:
if !o.status.success() {
// 可能打印 stderr 并返回。
}
英文:
Err
returned from output()
means spawning the process failed. It means nothing about the success/failure of the process itself. You need to check the ExitStatus
:
if !o.status.success() {
// Probably print stderr and bail.
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论