async_anyhow_logger/
lib.rs

1use anyhow::{Context, Result};
2use futures::Future;
3use std::fmt::Display;
4
5/// Catch an error from an asynchronous function, passing it to
6/// the [error logger](https://docs.rs/log/0.4/log/macro.error.html) with a static context.
7///
8/// See [anyhow::Context::context](https://docs.rs/anyhow/1.0/anyhow/trait.Context.html#tymethod.context)
9pub async fn catch_context<F>(context: &'static str, future: F)
10where
11	F: Future<Output = Result<()>>,
12{
13	if let Err(err) = future.await.context(context) {
14		log::error!("{:?}", err);
15	}
16}
17
18/// Catch an error from an asynchronous function, passing it to
19/// the [error logger](https://docs.rs/log/0.4/log/macro.error.html) with a context lazily evaluated from a closure.
20///
21/// See [anyhow::Context::with_context](https://docs.rs/anyhow/1.0/anyhow/trait.Context.html#tymethod.with_context)
22pub async fn catch_with_context<O, C, F>(context: C, future: F)
23where
24	O: Display + Send + Sync + 'static,
25	C: FnOnce() -> O,
26	F: Future<Output = Result<()>>,
27{
28	if let Err(err) = future.await.with_context(context) {
29		log::error!("{:?}", err);
30	}
31}
32
33/// Catch an error from an asynchronous function, passing it to the [error logger](https://docs.rs/log/0.4/log/macro.error.html).
34pub async fn catch<F>(future: F)
35where
36	F: Future<Output = Result<()>>,
37{
38	if let Err(err) = future.await {
39		log::error!("{:?}", err);
40	}
41}