Reputation: 11
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
Reputation: 431299
No, this does not happen, and probably cannot for multiple reasons:
?
would be a non-starter.?
can be used for other types besides Result
, such as Option
or Poll
. Should those be logged to a file?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