Skip to content

Commit 8b59aba

Browse files
committed
Define iptables error
1 parent 1458e1b commit 8b59aba

3 files changed

Lines changed: 33 additions & 7 deletions

File tree

Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[package]
22
name = "iptables"
3-
version = "0.4.0"
3+
version = "0.4.1"
44
authors = ["Navid Fathollahzade <yaa110@gmail.com>", "Pit Kleyersburg <pitkley@googlemail.com>"]
55
edition = "2018"
66
description = "Rust bindings for iptables"

src/error.rs

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
use std::convert::From;
2+
use std::error::Error;
3+
use std::fmt;
4+
use std::process::Output;
5+
6+
#[derive(Debug)]
7+
pub struct IptablesError {
8+
pub code: i32,
9+
pub msg: String,
10+
}
11+
12+
impl fmt::Display for IptablesError {
13+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
14+
write!(f, "code: {}, msg: {}", self.code, self.msg)
15+
}
16+
}
17+
18+
impl From<Output> for IptablesError {
19+
fn from(output: Output) -> Self {
20+
Self {
21+
code: output.status.code().unwrap_or(-1),
22+
msg: String::from_utf8_lossy(output.stderr.as_slice()).into(),
23+
}
24+
}
25+
}
26+
27+
impl Error for IptablesError {}

src/lib.rs

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,13 @@
1414
//! assert!(ipt.delete_chain("nat", "NEWCHAINNAME").is_ok());
1515
//! ```
1616
17+
pub mod error;
18+
19+
use error::IptablesError;
1720
use lazy_static::lazy_static;
1821
use nix::fcntl::{flock, FlockArg};
1922
use regex::{Match, Regex};
23+
use std::convert::From;
2024
use std::error::Error;
2125
use std::ffi::OsStr;
2226
use std::fs::File;
@@ -60,12 +64,7 @@ fn error_from_str(msg: &str) -> Box<dyn Error> {
6064

6165
fn output_to_result(output: Output) -> Result<(), Box<dyn Error>> {
6266
if !output.status.success() {
63-
let msg = format!(
64-
"iptables returned non-zero status code: {} - {}",
65-
output.status.code().unwrap_or(-1),
66-
String::from_utf8_lossy(output.stderr.as_slice()),
67-
);
68-
return Err(error_from_str(msg.as_str()));
67+
return Err(Box::new(IptablesError::from(output)));
6968
}
7069
Ok(())
7170
}

0 commit comments

Comments
 (0)