将Rust crate以与主函数退出时相同的方式格式化错误。

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

Getting the anyhow Rust crate to format an error like it does when when exiting the main function

问题

添加 anyhow crate 到一个空的 Rust 项目并运行以下代码会给你输出 Error: error,这正是我想要的:

use anyhow::anyhow;

fn error() -> anyhow::Result<()> {
    Err(anyhow!("error"))
}

fn main() -> anyhow::Result<()> {
    error()
}

然而,运行以下代码只会输出 error

use anyhow::anyhow;

fn error() -> anyhow::Result<()> {
    Err(anyhow!("error"))
}

fn main() {
    if let Err(error) = error() {
        println!("{:?}", error);
    }
}

我还尝试使用 "{:?}",但这同样只会打印 error

文档中说到:

Debug 格式 "{:?}" 会包括你的回溯信息,如果有的话。请注意,如果你从 fn main 中返回一个错误而不是显式打印它,那么这将是你默认获得的表示。

Error: Failed to read instrs from ./path/to/instrs.json

Caused by:
    No such file or directory (os error 2)

我找不到源代码中添加额外 Error: 部分的地方,否则我可能可以自己找出答案。

英文:

Adding the anyhow crate to a blank Rust project and running the following code gives you the output Error: error, which I want:

use anyhow::anyhow;

fn error() -&gt; anyhow::Result&lt;()&gt; {
    Err(anyhow!(&quot;error&quot;))
}

fn main() -&gt; anyhow::Result&lt;()&gt; {
    error()
}

However, running the following code only outputs error:

use anyhow::anyhow;

fn error() -&gt; anyhow::Result&lt;()&gt; {
    Err(anyhow!(&quot;error&quot;))
}

fn main() {
    if let Err(error) = error() {
        println!(&quot;{:?}&quot;, error);
    }
}

I also tried using &quot;{}&quot; instead, but that also only lead to error being printed.

The documentation says the following:

> The Debug format “{:?}” includes your backtrace if one was captured. Note that this is the representation you get by default if you return an error from fn main instead of printing it explicitly yourself.
>
>
&gt; Error: Failed to read instrs from ./path/to/instrs.json
&gt;
&gt; Caused by:
&gt; No such file or directory (os error 2)
&gt;

I couldn't find the part of the source code that added the extra Error: , otherwise I could probably figure it out by myself.

答案1

得分: 2

额外的“Error:”与任何事情都无关,而与main()的行为有关,如果返回的Result是一个Err。你可以在此处查找ResultTermination实现的精确代码:

impl<T: Termination, E: fmt::Debug> Termination for Result<T, E> {
    fn report(self) -> ExitCode {
        match self {
            Ok(val) => val.report(),
            Err(err) => {
                io::attempt_print_to_stderr(format_args_nl!("Error: {err:?}"));
                ExitCode::FAILURE
            }
        }
    }
}

因此,如果你想在不同上下文中的输出中包含“Error:”,你需要自己添加它。

另请参阅:https://stackoverflow.com/questions/72054026/in-rust--what-happens-if-main-function-returns-err

英文:

The extra Error: is not related to anyhow, but rather how main() behaves if the returned Result is an Err. You can find the exact code within the implementation of Termination for Result:

impl&lt;T: Termination, E: fmt::Debug&gt; Termination for Result&lt;T, E&gt; {
    fn report(self) -&gt; ExitCode {
        match self {
            Ok(val) =&gt; val.report(),
            Err(err) =&gt; {
                io::attempt_print_to_stderr(format_args_nl!(&quot;Error: {err:?}&quot;));
                ExitCode::FAILURE
            }
        }
    }
}

So if you want Error: included in the output in a different context, you'll have to add it yourself.

See also: https://stackoverflow.com/questions/72054026/in-rust-what-happens-if-main-function-returns-err

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

发表评论

匿名网友

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

确定