Clean up error handling
This commit is contained in:
@@ -23,7 +23,6 @@ macro_rules! format_if_error {
|
||||
|
||||
pub struct Error {
|
||||
pub exit_code: i32,
|
||||
pub action: String,
|
||||
pub text: String,
|
||||
}
|
||||
|
||||
@@ -35,7 +34,7 @@ impl Error {
|
||||
}
|
||||
|
||||
pub fn from_text(text: String) -> Error {
|
||||
Error{exit_code: Self::DEFAULT_EXITCODE, action: String::new(), text}
|
||||
Error{exit_code: Self::DEFAULT_EXITCODE, text}
|
||||
}
|
||||
|
||||
pub fn from_error<T>(error: T) -> Error where T: std::fmt::Display {
|
||||
@@ -55,41 +54,26 @@ impl Error {
|
||||
}
|
||||
|
||||
pub fn try_or_new<T, S>(result: std::result::Result<T, S>) -> Result<T, Error> where S: std::fmt::Display {
|
||||
Self::try_or_new_with_action(String::new(), result)
|
||||
}
|
||||
|
||||
pub fn try_or_new_with_action<T, S>(action: String, result: std::result::Result<T, S>) -> Result<T, Error> where S: std::fmt::Display {
|
||||
match result {
|
||||
Ok(value) => Ok(value),
|
||||
Err(error) => Err(Error{exit_code: Self::DEFAULT_EXITCODE, action, text: error.to_string()}),
|
||||
Err(error) => Err(Error{exit_code: Self::DEFAULT_EXITCODE, text: error.to_string()}),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn ok_or_new<T, F>(option: Option<T>, error_text: F) -> Result<T, Error> where F: Fn () -> String{
|
||||
Ok(option.ok_or(Error::from_callback(error_text))?)
|
||||
}
|
||||
|
||||
pub fn with_action(mut self, action: &str) -> Error {
|
||||
self.action = action.to_owned();
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Error {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
if self.action.is_empty() {
|
||||
write!(f, "{}", self.text)
|
||||
}
|
||||
|
||||
else {
|
||||
write!(f, "{}:{}", self.action, self.text)
|
||||
}
|
||||
write!(f, "{}", self.text)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::convert::From<std::io::Error> for Error {
|
||||
fn from(error: std::io::Error) -> Self {
|
||||
Error{exit_code: -1, action: String::new(), text: error.to_string()}
|
||||
Error{exit_code: -1, text: error.to_string()}
|
||||
}
|
||||
}
|
||||
|
||||
|
Reference in New Issue
Block a user