future_utils/
log_error.rs

1use std::fmt::Display;
2use futures::{Async, Future};
3use void::Void;
4use log::LogLevel;
5
6/// Wraps a future which returns `()` and logs its error if it fails. `LogError` itself cannot fail
7/// and will always resolve to `()`.
8pub struct LogError<F> {
9    future: F,
10    level: LogLevel,
11    description: &'static str,
12}
13
14impl<F> LogError<F> {
15    pub fn new(
16        future: F,
17        level: LogLevel,
18        description: &'static str,
19    ) -> LogError<F> {
20        LogError {
21            future,
22            level,
23            description,
24        }
25    }
26}
27
28impl<F> Future for LogError<F>
29where
30    F: Future<Item=()>,
31    F::Error: Display,
32{
33    type Item = ();
34    type Error= Void;
35
36    fn poll(&mut self) -> Result<Async<()>, Void> {
37        match self.future.poll() {
38            Ok(x) => Ok(x),
39            Err(e) => {
40                log!(self.level, "{}: {}", self.description, e);
41                Ok(Async::Ready(()))
42            },
43        }
44    }
45}
46