Skip to content

Commit

Permalink
改进错误处理 (#11)
Browse files Browse the repository at this point in the history
* Format

* Abort on error
  • Loading branch information
Nugine authored Apr 27, 2021
1 parent 2827601 commit 72b890d
Show file tree
Hide file tree
Showing 3 changed files with 224 additions and 91 deletions.
4 changes: 2 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

41 changes: 41 additions & 0 deletions src/aoe.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
use std::{fmt, process};

pub trait AbortOnError<T>: Sized {
fn aoe(self) -> T;

fn aoe_msg(self, msg: impl fmt::Display) -> T;
}

impl<T, E> AbortOnError<T> for Result<T, E>
where
E: fmt::Display,
{
#[track_caller]
fn aoe(self) -> T {
match self {
Ok(value) => value,
Err(err) => panic!("Error: {}", err),
}
}

#[track_caller]
fn aoe_msg(self, msg: impl fmt::Display) -> T {
match self {
Ok(value) => value,
Err(err) => panic!("{}: {}", msg, err),
}
}
}

pub fn register() {
std::panic::set_hook(Box::new(|info| {
let msg = info.payload().downcast_ref::<String>();
let loc = info.location();
if let (Some(msg), Some(loc)) = (msg, loc) {
eprintln!("[{}:{}:{}] {}", loc.file(), loc.line(), loc.column(), msg);
} else {
eprintln!("{}", info)
}
process::exit(1);
}));
}
Loading

0 comments on commit 72b890d

Please sign in to comment.