Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get file and line number where an error was returned?

Suppose I call function f().unwrap() which calls calls function g. The g function returns an Error wrapped in Result, and f propagates this error. Then I get the message that thread panicked at line where I called f().unwrap().

I would like to know is the place where error was returned, i.e. where g returned error. This would be much more informative, is there any way to achieve this?

like image 325
aboilque Avatar asked Nov 02 '25 03:11

aboilque


2 Answers

If you return anyhow::Error, and you turn on the backtrace feature of anyhow, you can retrieve a backtrace from the error if you will set the environment variable RUST_BACKTRACE or RUST_LIB_BACKTRACE to 1:

let error: anyhow::Error;
eprintln!("{}", error.backtrace());
like image 59
Chayim Friedman Avatar answered Nov 03 '25 21:11

Chayim Friedman


You can do it but you have to collect and attach the info yourself:

With anyhow you can add context to an error with the context method.

fn main() {
    f().unwrap();
}

fn f() -> Result<(), anyhow::Error> {
    g().map_err(|e| e.context(format!("at {}:{}:{}", file!(), line!(), column!())))?;
    Err(anyhow::anyhow!("some other error"))
}

fn g() -> Result<(), anyhow::Error> {
    Err(anyhow::anyhow!("oh noes"))
}

Or you can wrap the error in your own error type containing the info.

fn main() {
    f().unwrap();
}

#[derive(Debug)]
struct Error {
    file: &'static str,
    line: u32,
    column: u32,
    error: GError,
}

#[derive(Debug)]
struct GError;

fn f() -> Result<(), Error> {
    g().map_err(|e| Error {
        file: file!(),
        line: line!(),
        column: column!(),
        error: e,
    })
}

fn g() -> Result<(), GError> {
    Err(GError)
}
like image 22
cafce25 Avatar answered Nov 03 '25 21:11

cafce25



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!