printerrors

This commit is contained in:
Alex Janka 2024-02-12 09:32:07 +11:00
commit 8f437e0be9
5 changed files with 70 additions and 0 deletions

1
.gitignore vendored Normal file
View file

@ -0,0 +1 @@
/target

16
Cargo.lock generated Normal file
View file

@ -0,0 +1,16 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "alex-utils"
version = "0.1.0"
dependencies = [
"log",
]
[[package]]
name = "log"
version = "0.4.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5e6163cb8c49088c2c36f57875e58ccd8c87c7427f7fbd50ea6710b2f3f2e8f"

11
Cargo.toml Normal file
View file

@ -0,0 +1,11 @@
[package]
name = "alex-utils"
version = "0.1.0"
edition = "2021"
[features]
default = ["log"]
log = ["dep:log"]
[dependencies]
log = { version = "0.4", optional = true }

3
src/lib.rs Normal file
View file

@ -0,0 +1,3 @@
mod print_errors;
pub use print_errors::PrintErrors;

39
src/print_errors.rs Normal file
View file

@ -0,0 +1,39 @@
pub trait PrintErrors {
type Inner;
fn some_or_print(self) -> Option<Self::Inner>;
fn some_or_print_with_context(self, context: &str) -> Option<Self::Inner>;
}
impl<T, E> PrintErrors for Result<T, E>
where
E: std::error::Error,
{
type Inner = T;
fn some_or_print(self) -> Option<Self::Inner> {
match self {
Ok(val) => Some(val),
Err(e) => {
#[cfg(feature = "log")]
log::error!("{e:?}");
#[cfg(not(feature = "log"))]
println!("{e:?}");
None
}
}
}
fn some_or_print_with_context(self, context: &str) -> Option<Self::Inner> {
match self {
Ok(val) => Some(val),
Err(e) => {
#[cfg(feature = "log")]
log::error!("{context}: {e:?}");
#[cfg(not(feature = "log"))]
println!("{context}: {e:?}");
None
}
}
}
}