Find where error occured

Hi everybody

I'm not a Rust expert but I learned the ? operator on error handling is pretty nice.
Now I've used it quite a lot and I get an error somewhere in the code, but when I print the error I get only the stack trace of where I print the error and I have no chance on finding out where the error occued. Is there a way to find out where an error occured?

Here is an example:

use std::fmt::{Display, Formatter};

fn main() {
    match function_possible_error_one() {
        Ok(_) => {}
        Err(e) => {
            panic!("An error occured but where?: {:?}", e);
        }
    }
    println!("Program finsihed successfully");
}

fn function_possible_error_one() -> Result<(), MyError> {
    Ok(function_possible_error_two()?)
}

fn function_possible_error_two() -> Result<(), MyError> {
    Ok(function_possible_error_three()?)
}

fn function_possible_error_three() -> Result<(), MyError> {
    Err(MyError::Error1("File not found".to_string()))
}

#[derive(Debug)]
enum MyError {
    Error1(String),
}

impl Display for MyError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            MyError::Error1(e) => write!(f, "{}", e),
        }
    }
}

impl std::error::Error for MyError {}

Errors are just normal values, so if you want a backtrace from where the error it was created you'll need to capture it yourself and store it inside your error value.

The anyhow crate will automatically do this for you when you construct an anyhow::Error (possibly directly via Error::msg() or the anyhow!() macro, or indirectly via ?). It gets shown automatically when you debug print the Error and have the RUST_BACKTRACE environment variable set and the nightly feature lets you use the backtrace() method to get a reference to the backtrace directly.

1 Like