Even nicer logging: Add ok_or_log() and more (#2284)

Co-authored-by: Floris Bruynooghe <flub@devork.be>
This commit is contained in:
Hocuri
2021-03-13 21:06:37 +01:00
committed by GitHub
parent 4ab90f7069
commit 98fc559536
5 changed files with 90 additions and 47 deletions

View File

@@ -24,7 +24,6 @@ use std::time::{Duration, SystemTime};
use async_std::task::{block_on, spawn};
use num_traits::{FromPrimitive, ToPrimitive};
use deltachat::accounts::Accounts;
use deltachat::chat::{ChatId, ChatVisibility, MuteDuration, ProtectionStatus};
use deltachat::constants::DC_MSG_ID_LAST_SPECIAL;
use deltachat::contact::{Contact, Origin};
@@ -34,6 +33,7 @@ use deltachat::key::DcKey;
use deltachat::message::MsgId;
use deltachat::stock_str::StockMessage;
use deltachat::*;
use deltachat::{accounts::Accounts, log::LogExt};
mod dc_array;
@@ -3451,15 +3451,11 @@ pub unsafe extern "C" fn dc_str_unref(s: *mut libc::c_char) {
}
trait ResultExt<T, E> {
/// Like `log_err()`, but:
/// - returns the default value instead of an Err value.
/// - emits an error instead of a warning for an [Err] result. This means
/// that the error will be shown to the user in a small pop-up.
fn unwrap_or_log_default(self, context: &context::Context, message: &str) -> T;
/// Log a warning to a [ContextWrapper] for an [Err] result.
///
/// Does nothing for an [Ok].
///
/// You can do this as soon as the wrapper exists, it does not
/// have to be open (which is required for the `warn!()` macro).
fn log_err(self, wrapper: &Context, message: &str) -> Result<T, E>;
}
impl<T: Default, E: std::fmt::Display> ResultExt<T, E> for Result<T, E> {
@@ -3472,14 +3468,6 @@ impl<T: Default, E: std::fmt::Display> ResultExt<T, E> for Result<T, E> {
}
}
}
fn log_err(self, ctx: &Context, message: &str) -> Result<T, E> {
self.map_err(|err| {
// We are using Anyhow's .context() and to show the inner error, too, we need the {:#}:
warn!(ctx, "{}: {:#}", message, err);
err
})
}
}
trait ResultNullableExt<T> {