mirror of
https://github.com/jht5945/rust_util.git
synced 2025-12-27 15:40:03 +08:00
feat: add simple_error
This commit is contained in:
49
src/lib.rs
49
src/lib.rs
@@ -2,7 +2,12 @@
|
||||
extern crate lazy_static;
|
||||
extern crate term;
|
||||
|
||||
use std::io::{ Error, ErrorKind };
|
||||
use std::error::Error;
|
||||
use std::io::Error as IoError;
|
||||
use std::io::ErrorKind;
|
||||
use std::fmt::Display;
|
||||
use std::fmt::Formatter;
|
||||
use std::fmt::Result as FmtResult;
|
||||
|
||||
pub mod util_io;
|
||||
pub mod util_os;
|
||||
@@ -40,12 +45,44 @@ pub mod util_git;
|
||||
($e: expr) => ( match $e { Some(o) => o, None => return, } )
|
||||
}
|
||||
|
||||
pub type XResult<T> = Result<T, Box<dyn std::error::Error>>;
|
||||
pub type XResult<T> = Result<T, Box<dyn Error>>;
|
||||
|
||||
pub fn new_box_error(m: &str) -> Box<dyn std::error::Error> {
|
||||
Box::new(Error::new(ErrorKind::Other, m))
|
||||
pub fn new_box_error(m: &str) -> Box<dyn Error> {
|
||||
Box::new(IoError::new(ErrorKind::Other, m))
|
||||
}
|
||||
|
||||
pub fn new_box_ioerror(m: &str) -> Box<dyn std::error::Error> {
|
||||
Box::new(Error::new(ErrorKind::Other, m))
|
||||
pub fn new_box_ioerror(m: &str) -> Box<dyn Error> {
|
||||
Box::new(IoError::new(ErrorKind::Other, m))
|
||||
}
|
||||
|
||||
#[macro_export] macro_rules! simple_error {
|
||||
($($arg:tt)+) => ( Err(rust_util::SimpleError::new(format!($($arg)+)).into()) )
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct SimpleError {
|
||||
pub message: String,
|
||||
pub source: Option<Box<dyn Error>>,
|
||||
}
|
||||
|
||||
impl SimpleError {
|
||||
pub fn new(message: String) -> Self {
|
||||
Self { message, source: None }
|
||||
}
|
||||
|
||||
pub fn new2(message: String, source: Box<dyn Error>) -> Self {
|
||||
Self { message, source: Some(source) }
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for SimpleError {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
|
||||
match &self.source {
|
||||
None => write!(f, "SimpleErorr, message: {}", self.message),
|
||||
Some(e) => write!(f, "SimpleErorr, message: {}, source erorr: {}", self.message, e),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for SimpleError {}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user