Improve creation of error messages

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

View File

@ -2,7 +2,7 @@ use super::{*, SectorWriter, {CDDesc, Error}};
use super::super::types::{helper::{DirectoryRecordMember, PathTableMember}, layout::Layout, *};
use builder::SubModeBuilder;
use cdtypes::types::{cdstring::{AString, DString}, date::*, dir_record::*, helper::{round_bytes_mode2_form1, sector_count_mode2_form1}, path_table::*, pvd as cd_pvd, lsb_msb::*, sector::Mode2Form1};
use tool_helper::{BufferedInputFile, open_input_file_buffered};
use tool_helper::{BufferedInputFile, construct_from_error_if as format_if_error, open_input_file_buffered};
use std::io::{Read, Seek, SeekFrom};
const ROOT_DIR_NAME:&'static str = "\x00";
@ -159,8 +159,8 @@ fn process_system_area(system_area: &SystemArea, sec_writer: &mut dyn SectorWrit
return Err(Error::from_text(format!("System Area required to start at sector 0 of Track - found LBA: {}", system_area_lba)));
}
if let Some(license_file) = &system_area.license_file_path {
let license_file = open_input_file_buffered(license_file)?;
if let Some(license_path) = &system_area.license_file_path {
let license_file = format_if_error!(open_input_file_buffered(license_path), "Loading license file from {} failed with: {error_text}", license_path.to_string_lossy())?;
write_license_file(sec_writer, license_file)
}

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)?))
}