Add ResultExt

This commit is contained in:
topjohnwu
2023-05-05 23:57:34 -07:00
parent c0d1bf63bc
commit c0c9204848
2 changed files with 37 additions and 10 deletions

View File

@@ -1,4 +1,4 @@
use std::fmt::Arguments;
use std::fmt::{Arguments, Display};
use std::io::{stderr, stdout, Write};
use std::process::exit;
@@ -155,3 +155,34 @@ macro_rules! debug {
macro_rules! debug {
($($args:tt)+) => {};
}
pub trait ResultExt {
fn ok_or_log(&self);
fn ok_or_msg(&self, args: Arguments);
fn log_on_error(&self) -> &Self;
fn msg_on_error(&self, args: Arguments) -> &Self;
}
impl<R, E: Display> ResultExt for Result<R, E> {
fn ok_or_log(&self) {
if let Err(e) = self {
error!("{}", e);
}
}
fn ok_or_msg(&self, args: Arguments) {
if let Err(e) = self {
error!("{}: {}", args, e);
}
}
fn log_on_error(&self) -> &Self {
self.ok_or_log();
self
}
fn msg_on_error(&self, args: Arguments) -> &Self {
self.ok_or_msg(args);
self
}
}