shepmaster / snafu

Easily assign underlying errors into domain-specific errors while adding context
https://docs.rs/snafu/
Apache License 2.0
1.39k stars 60 forks source link

`Report` print doesn't prefix with "Error: " #452

Closed DerickEddington closed 3 months ago

DerickEddington commented 3 months ago

In src/report.md, it says the example's printed output will be prefixed with "Error: " [1]:

Error: Unable to frobnicate the mumbletypeg
[...]

But when the example, or any other program using Report as the return type of the main function, is actually run, its output is not prefixed like that, and its actual output is like:

Unable to frobnicate the mumbletypeg
[...]

I'm guessing the original intention was for this to print the "Error: " prefix, because src/report.md saying that it will is part of the same commit where the actual formatting was introduced [2].

I'd prefer if this did print the prefix, because I rely on that to more easily notice when there was an error (vs. non-error printed output), and because that would be more consistent with the std library's printing [3] and with other error-helping libraries IIRC.

Maybe fixing this is as simple as:

--- a/src/report.rs
+++ b/src/report.rs
@@ -188,7 +188,7 @@ where
         match self.0 {
             Ok(()) => ExitCode::SUCCESS,
             Err(e) => {
-                eprintln!("{}", ReportFormatter(&e));
+                eprintln!("Error: {}", ReportFormatter(&e));

                 #[cfg(feature = "unstable-provider-api")]
                 {
shepmaster commented 3 months ago

The problem arises from the fact that we support older versions of Rust:

[dependencies]
snafu = { version = "0.8.2", default-features = false }
use snafu::prelude::*;

#[snafu::report]
fn main() -> Result<(), Error> {
    Err(Error)
}

#[derive(Debug, Snafu)]
struct Error;
% cargo run
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.01s
     Running `target/debug/whawha`
Error: Error

When targeting older versions of Rust, we transform main into

fn main() -> Result<(), Report<Error>>

When targeting newer versions:

fn main() -> Report<Error>

As you said, the standard library is the one that adds the Error: prefix when printing out the Result.


Your fix seems like the right direction, we just need to ensure that we don't end up printing Error: Error: ... when older versions of Rust are targeted.