Improve creation of error messages

This commit is contained in:
2022-11-16 04:36:25 +01:00
parent 9cb04e2380
commit c638782fa8
2 changed files with 41 additions and 3 deletions

View File

@@ -7,6 +7,20 @@ pub type BufferedInputFile = BufReader<std::fs::File>;
pub type Output = Box<dyn Write>;
pub type Input = Box<dyn Read>;
#[macro_export]
macro_rules! construct_from_error_if {
($result:expr, $format_text:literal) => {
tool_helper::callback_if_error($result, |error_text| {
format!($format_text, error_text=error_text)
})
};
($result:expr, $format_text:literal, $($arg:expr)*) => {
tool_helper::callback_if_error($result, |error_text| {
format!($format_text, $($arg),*, error_text=error_text)
})
};
}
pub trait ErrorString {
fn to_string(self) -> String;
}
@@ -101,6 +115,30 @@ impl<T: ErrorString> std::convert::From<T> for Error {
}
}
pub fn prefix_if_error<T>(prefix: &str, result: Result<T, Error>) -> Result<T, Error> {
match result {
Ok(value) => Ok(value),
Err(mut error) => {
let mut new_text = String::from(prefix);
new_text.push_str(error.text.as_str());
error.text = new_text;
Err(error)
},
}
}
pub fn callback_if_error<F: Fn(String) -> String, T>(result: Result<T, Error>, callback: F) -> Result<T, Error> {
match result {
Ok(value) => Ok(value),
Err(mut error) => {
error.text = callback(error.text);
Err(error)
}
}
}
pub fn open_output_file(output_path: &PathBuf) -> Result<BufWriter<std::fs::File>, Error> {
Ok(std::io::BufWriter::new(std::fs::File::create(output_path)?))
}