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
42
43
44
45
use std::fmt::Display;
use futures::{Async, Stream};
use void::Void;
use log::LogLevel;

/// Removes the errors from a stream and logs them.
pub struct LogErrors<S> {
    stream: S,
    level: LogLevel,
    description: &'static str,
}

impl<S> LogErrors<S> {
    pub fn new(
        stream: S,
        level: LogLevel,
        description: &'static str,
    ) -> LogErrors<S> {
        LogErrors {
            stream,
            level,
            description,
        }
    }
}

impl<S> Stream for LogErrors<S>
where
    S: Stream,
    S::Error: Display,
{
    type Item = S::Item;
    type Error = Void;

    fn poll(&mut self) -> Result<Async<Option<S::Item>>, Void> {
        match self.stream.poll() {
            Ok(x) => Ok(x),
            Err(e) => {
                log!(self.level, "{}: {}", self.description, e);
                Ok(Async::NotReady)
            },
        }
    }
}