Ok() 在匹配表达式中处理错误消息,而不是 Err()。

huangapple go评论91阅读模式
英文:

Ok() is handling error message instead of Err() in match expression

问题

我执行命令:

  1. use std::process::Command;
  2. pub fn search(query: &str, flag: &str) -> Vec<String> {
  3. let command = format!("xdotool search --onlyvisible {} {}", flag, query);
  4. let output = Command::new("sh").arg("-c").arg(command).output();
  5. match output {
  6. Ok(o) => {
  7. println!("Success message: {:?}", o);
  8. String::from_utf8_lossy(&o.stdout)
  9. .lines()
  10. .map(|s| s.to_owned())
  11. .collect()
  12. }
  13. Err(err) => {
  14. eprintln!(
  15. "Error message: {:?}",
  16. String::from_utf8_lossy(&err.to_string().as_bytes())
  17. .trim()
  18. .to_owned()
  19. );
  20. Vec::new()
  21. }
  22. }
  23. }

如果我使用错误的 flag,我会得到一个错误消息,但它被处理为 search() 函数中的 Ok()。为什么会这样?如何让 Err() 处理错误消息呢?

英文:

I execute commands:

  1. use std::process::Command;
  2. pub fn search(query: &amp;str, flag: &amp;str) -&gt; Vec&lt;String&gt; {
  3. let command = format!(&quot;xdotool search --onlyvisible {} {}&quot;, flag, query);
  4. let output = Command::new(&quot;sh&quot;).arg(&quot;-c&quot;).arg(command).output();
  5. match output {
  6. Ok(o) =&gt; {
  7. println!(&quot;Success message: {:?}&quot;, o);
  8. String::from_utf8_lossy(&amp;o.stdout)
  9. .lines()
  10. .map(|s| s.to_owned())
  11. .collect()
  12. }
  13. Err(err) =&gt; {
  14. eprintln!(
  15. &quot;Error message: {:?}&quot;,
  16. String::from_utf8_lossy(&amp;err.to_string().as_bytes())
  17. .trim()
  18. .to_owned()
  19. );
  20. Vec::new()
  21. }
  22. }
  23. }

If I use a wrong flag, I get an error message, but it's being handled of Ok() in the search() function:

  1. Success message: Output { status: ExitStatus(unix_wait_status(256)), stdout: &quot;&quot;, stderr: &quot;search: unrecognized ...

Why is this? And how to make Err() handle the error message instead?

答案1

得分: 7

output() 返回的 Err 表示生成进程失败。 这与进程本身的成功/失败无关。 您需要检查 ExitStatus

  1. if !o.status.success() {
  2. // 可能打印 stderr 并返回。
  3. }
英文:

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:

  1. if !o.status.success() {
  2. // Probably print stderr and bail.
  3. }

huangapple
  • 本文由 发表于 2023年2月24日 01:10:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/75548110.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定