dtolnay/anyhow

Attach line & file info to anyhow::Error and anyhow::Context

vultix opened this issue · 4 comments

First off, thank you for this wonderful library!

Context

It's often difficult to find where in your code an error occurred. Rust's backtraces help with this, but are often so verbose that it's still difficult.

Proposal

It would be great if you could simply glance at the error output to get file and line information. This could be implemented using #[track_caller] and can be optionally turned on using a feature flag.

I'm not sure what format you'll want, but I'm imagining something like this:

Error: Failed to parse file: hello.txt @ main.rs:7:10

Caused by:
    0: Unable to convert this string into a float: '1.5a' @ main.rs:19:24
    1: invalid float literal @ main.rs:25:32
    
Stack backtrace:
...

I'm willing to make a PR if you like this feature!

I would like to see this as a debug feature. Off by default for release builds.

For the time being I created this macro for my use:

#[cfg(feature = "file_lines")]
macro_rules! line_leader {
    () => {
        format!("{}:{}", file!(), line!());
    };
}

#[cfg(feature = "file_lines")]
macro_rules! f_context {
    ($msg:literal $(,)?) => {
        format!("{} {}", line_leader!(), $msg);
    };
    ($fmt:expr, $($arg:tt)*) => (
        format!("{} {}", line_leader!(), format!($fmt, $($arg)*));
    )
}
#[cfg(not(feature = "file_lines"))]
macro_rules! f_context {
    ($msg:literal $(,)?) => {
        $msg
    };
    ($fmt:expr, $($arg:tt)*) => (
        format!($fmt, $($arg)*);
    )
}

I use it like this:

            can_error(&arg)
                .context(f_context!("Did error with {:?}", &arg));
cargo run --features=file_lines -- -a arg

src\main.rs:123 Error: This demo failed to execute.

Caused by:
    src\main.rs:456 Did error with "arg"

@dtolnay is the https://github.com/dtolnay/anyhow/tree/location branch still planned to be released? Right now we're trying to extract location via the backtraces and as my colleague kindly put it, it's "gnarly".

I would like to see this as a debug feature. Off by default for release builds.

i dont agree with this, i think it can be a useful feature for release builds for debugging bugs, i'd rather have this as a separate feature