use tracing::{debug, warn};
pub fn log_error<F, T, E>(operation: F, context: &str) -> Option<T>
where
F: FnOnce() -> Result<T, E>,
E: std::fmt::Display,
{
match operation() {
Ok(value) => Some(value),
Err(e) => {
warn!("{}: {}", context, e);
None
}
}
}
pub async fn log_error_async<F, Fut, T, E>(operation: F, context: &str) -> Option<T>
where
F: FnOnce() -> Fut,
Fut: std::future::Future<Output = Result<T, E>>,
E: std::fmt::Display,
{
match operation().await {
Ok(value) => Some(value),
Err(e) => {
warn!("{}: {}", context, e);
None
}
}
}
pub fn with_fallback<F1, F2, T, E>(primary: F1, fallback: F2, context: &str) -> T
where
F1: FnOnce() -> Result<T, E>,
F2: FnOnce() -> T,
E: std::fmt::Display,
{
match primary() {
Ok(value) => value,
Err(e) => {
warn!("{}: {}", context, e);
fallback()
}
}
}
pub async fn with_fallback_async<F1, Fut1, F2, Fut2, T, E>(
primary: F1,
fallback: F2,
context: &str,
) -> T
where
F1: FnOnce() -> Fut1,
Fut1: std::future::Future<Output = Result<T, E>>,
F2: FnOnce() -> Fut2,
Fut2: std::future::Future<Output = T>,
E: std::fmt::Display,
{
match primary().await {
Ok(value) => value,
Err(e) => {
warn!("{}: {}", context, e);
fallback().await
}
}
}
pub fn with_default<F, T, E>(operation: F, default: T, context: &str) -> T
where
F: FnOnce() -> Result<T, E>,
E: std::fmt::Display,
{
match operation() {
Ok(value) => value,
Err(e) => {
debug!("{}: {}, using default", context, e);
default
}
}
}
pub async fn with_default_async<F, Fut, T, E>(operation: F, default: T, context: &str) -> T
where
F: FnOnce() -> Fut,
Fut: std::future::Future<Output = Result<T, E>>,
E: std::fmt::Display,
{
match operation().await {
Ok(value) => value,
Err(e) => {
debug!("{}: {}, using default", context, e);
default
}
}
}
pub fn err_option_to_result<T, F>(opt: Option<T>, context: F) -> Result<T, String>
where
F: FnOnce() -> String,
{
opt.ok_or_else(context)
}
pub fn result_to_option<T, E>(result: Result<T, E>, context: &str) -> Option<T>
where
E: std::fmt::Display,
{
match result {
Ok(value) => Some(value),
Err(e) => {
warn!("{}: {}", context, e);
None
}
}
}