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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
extern crate regex;
extern crate nix;

use std::{fmt, error, io, convert, num};

/// Defines the general error type of iptables crate
#[derive(Debug)]
pub enum IPTError {
    Io(io::Error),
    Regex(regex::Error),
    Nix(nix::Error),
    Parse(num::ParseIntError),
    Other(&'static str),
}

/// Defines the Result type of iptables crate
pub type IPTResult<T> = Result<T, IPTError>;

impl fmt::Display for IPTError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            IPTError::Io(ref err) => write!(f, "{}", err),
            IPTError::Regex(ref err) => write!(f, "{}", err),
            IPTError::Nix(ref err) => write!(f, "{}", err),
            IPTError::Parse(ref err) => write!(f, "{}", err),
            IPTError::Other(ref message) => write!(f, "{}", message),
        }
    }
}

impl error::Error for IPTError {
    fn description(&self) -> &str {
        match *self {
            IPTError::Io(ref err) => err.description(),
            IPTError::Regex(ref err) => err.description(),
            IPTError::Nix(ref err) => err.description(),
            IPTError::Parse(ref err) => err.description(),
            IPTError::Other(ref message) => message,
        }
    }

    fn cause(&self) -> Option<&error::Error> {
        match *self {
            IPTError::Io(ref err) => Some(err),
            IPTError::Regex(ref err) => Some(err),
            IPTError::Nix(ref err) => Some(err),
            IPTError::Parse(ref err) => Some(err),
            _ => Some(self),
        }
    }
}

impl convert::From<io::Error> for IPTError {
    fn from(err: io::Error) -> Self {
        IPTError::Io(err)
    }
}

impl convert::From<regex::Error> for IPTError {
    fn from(err: regex::Error) -> Self {
        IPTError::Regex(err)
    }
}

impl convert::From<nix::Error> for IPTError {
    fn from(err: nix::Error) -> Self {
        IPTError::Nix(err)
    }
}

impl convert::From<num::ParseIntError> for IPTError {
    fn from(err: num::ParseIntError) -> Self {
        IPTError::Parse(err)
    }
}

impl convert::From<&'static str> for IPTError {
    fn from(err: &'static str) -> Self {
        IPTError::Other(err)
    }
}