1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
use anyhow::{Context, Result};
use futures::Future;
use std::fmt::Display;

/// Catch an error from an asynchronous function, passing it to
/// the [error logger](https://docs.rs/log/0.4/log/macro.error.html) with a static context.
///
/// See [anyhow::Context::context](https://docs.rs/anyhow/1.0/anyhow/trait.Context.html#tymethod.context)
pub async fn catch_context<F>(context: &'static str, future: F)
where
	F: Future<Output = Result<()>>,
{
	if let Err(err) = future.await.context(context) {
		log::error!("{:?}", err);
	}
}

/// Catch an error from an asynchronous function, passing it to
/// the [error logger](https://docs.rs/log/0.4/log/macro.error.html) with a context lazily evaluated from a closure.
///
/// See [anyhow::Context::with_context](https://docs.rs/anyhow/1.0/anyhow/trait.Context.html#tymethod.with_context)
pub async fn catch_with_context<O, C, F>(context: C, future: F)
where
	O: Display + Send + Sync + 'static,
	C: FnOnce() -> O,
	F: Future<Output = Result<()>>,
{
	if let Err(err) = future.await.with_context(context) {
		log::error!("{:?}", err);
	}
}

/// Catch an error from an asynchronous function, passing it to the [error logger](https://docs.rs/log/0.4/log/macro.error.html).
pub async fn catch<F>(future: F)
where
	F: Future<Output = Result<()>>,
{
	if let Err(err) = future.await {
		log::error!("{:?}", err);
	}
}