1
0
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:
2021-01-01 18:58:04 +08:00
parent 1a3c8cbeb4
commit f0bd9a719a
4 changed files with 54 additions and 10 deletions

View File

@@ -1,6 +1,6 @@
[package]
name = "rust_util"
version = "0.6.24"
version = "0.6.25"
authors = ["Hatter Jiang <jht5945@gmail.com>"]
edition = "2018"
description = "Hatter's Rust Util"

View File

@@ -1,7 +1,9 @@
#[macro_use] extern crate rust_util;
use rust_util::XResult;
// cargo run --example log
fn main() {
fn main() -> XResult<()> {
std::env::set_var("LOGGER_LEVEL", "*");
println!(r##"env LOGGER_LEVEL set to:
debug or *
@@ -15,4 +17,6 @@ error or ^"##);
success!("Hello {}", "world!");
warning!("Hello {}", "world!");
failure!("Hello {}", "world!");
simple_error!("helloworld {}", 1)
}

View File

@@ -1,9 +1,12 @@
# help
aa:
_:
@just --list
# example log
log:
cargo run --example log
# publish
publish:
cargo publish

View File

@@ -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 {}