From 8b59aba80d45de636640a85c0fd25c1709643d14 Mon Sep 17 00:00:00 2001 From: Navid Date: Tue, 29 Dec 2020 01:07:37 +0330 Subject: [PATCH] Define iptables error --- Cargo.toml | 2 +- src/error.rs | 27 +++++++++++++++++++++++++++ src/lib.rs | 11 +++++------ 3 files changed, 33 insertions(+), 7 deletions(-) create mode 100644 src/error.rs diff --git a/Cargo.toml b/Cargo.toml index 8a142bc..69108f7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "iptables" -version = "0.4.0" +version = "0.4.1" authors = ["Navid Fathollahzade ", "Pit Kleyersburg "] edition = "2018" description = "Rust bindings for iptables" diff --git a/src/error.rs b/src/error.rs new file mode 100644 index 0000000..e58bf47 --- /dev/null +++ b/src/error.rs @@ -0,0 +1,27 @@ +use std::convert::From; +use std::error::Error; +use std::fmt; +use std::process::Output; + +#[derive(Debug)] +pub struct IptablesError { + pub code: i32, + pub msg: String, +} + +impl fmt::Display for IptablesError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "code: {}, msg: {}", self.code, self.msg) + } +} + +impl From for IptablesError { + fn from(output: Output) -> Self { + Self { + code: output.status.code().unwrap_or(-1), + msg: String::from_utf8_lossy(output.stderr.as_slice()).into(), + } + } +} + +impl Error for IptablesError {} diff --git a/src/lib.rs b/src/lib.rs index 50bd041..d730e8a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -14,9 +14,13 @@ //! assert!(ipt.delete_chain("nat", "NEWCHAINNAME").is_ok()); //! ``` +pub mod error; + +use error::IptablesError; use lazy_static::lazy_static; use nix::fcntl::{flock, FlockArg}; use regex::{Match, Regex}; +use std::convert::From; use std::error::Error; use std::ffi::OsStr; use std::fs::File; @@ -60,12 +64,7 @@ fn error_from_str(msg: &str) -> Box { fn output_to_result(output: Output) -> Result<(), Box> { if !output.status.success() { - let msg = format!( - "iptables returned non-zero status code: {} - {}", - output.status.code().unwrap_or(-1), - String::from_utf8_lossy(output.stderr.as_slice()), - ); - return Err(error_from_str(msg.as_str())); + return Err(Box::new(IptablesError::from(output))); } Ok(()) }