英文:
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() -> anyhow::Result<()> {
Err(anyhow!("error"))
}
fn main() -> anyhow::Result<()> {
error()
}
However, running the following code only outputs error
:
use anyhow::anyhow;
fn error() -> anyhow::Result<()> {
Err(anyhow!("error"))
}
fn main() {
if let Err(error) = error() {
println!("{:?}", error);
}
}
I also tried using "{}"
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.
>
>
> Error: Failed to read instrs from ./path/to/instrs.json
>
> Caused by:
> No such file or directory (os error 2)
>
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
。你可以在此处查找Result
的Termination
实现的精确代码:
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<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
}
}
}
}
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论