Jinshou He
Jinshou He

Reputation: 11

How do I log to a file when an error occurs while using the question mark (?) operator?

Motivation: I want to log file name, line number, function name, error code, etc to help analyze errors

Rust has ? to do error handling. I want to log info to a file if there is an error in ?. How to achieve this?

Code:

let a = do_some_function_may_return_error()?;   // Does it auto log the error info when error occurs?
let b = a.do_another_function_may_return_error()?; // Does it auto log the error info when error occurs?

Upvotes: 1

Views: 2004

Answers (1)

Shepmaster
Shepmaster

Reputation: 431299

No, this does not happen, and probably cannot for multiple reasons:

  1. Rust the language is intended to run on systems that don't even have the concept of files, so requiring it for something as fundamental as ? would be a non-starter.
  2. ? can be used for other types besides Result, such as Option or Poll. Should those be logged to a file?
  3. How would you even configure the file to log to?
  4. The error type of Result doesn't guarantee that it can be formatted as text.

Instead, I'd add an extension trait:

trait LogExt {
    fn log(self) -> Self;
}

impl<T, E> LogExt for Result<T, E>
where
    E: std::fmt::Display,
{
    fn log(self) -> Self {
        if let Err(e) = &self {
            eprintln!("An error happened: {}", e);
        }
        self
    }
}

This would be used before each ?:

fn main() -> Result<(), String> {
    fails().log()?;
    Ok(())
}

fn fails() -> Result<(), String> {
    Err("Oh no!".into())
}

Upvotes: 5

Related Questions