ipfw_rs/runtime_exception.rs
1
2/*-
3 * SPDX-License-Identifier: BSD-2-Clause
4 *
5 * Copyright (c) 2024 Aleksandr Morozov
6 * All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 *
12 * - Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * - Redistributions in binary form must reproduce the above
15 * copyright notice, this list of conditions and the following
16 * disclaimer in the documentation and/or other materials provided
17 * with the distribution.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
22 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
23 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
24 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
25 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
26 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
27 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
29 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30 * POSSIBILITY OF SUCH DAMAGE.
31 *
32 */
33
34use std::fmt;
35
36pub struct IpfwError
37{
38 err: nix::Error,
39 message: String,
40}
41
42impl IpfwError
43{
44 pub
45 fn new(msg: String) -> Self
46 {
47 return Self{ err: nix::Error::EINVAL, message: msg };
48 }
49
50 pub
51 fn new_empty() -> Self
52 {
53 return Self{ err: nix::Error::EINVAL, message: String::new() };
54 }
55
56 pub
57 fn new_nix_err(errn: nix::Error) -> Self
58 {
59 return Self{ err: errn, message: String::new() };
60 }
61
62 pub
63 fn get_errno(&self) -> nix::Error
64 {
65 return self.err;
66 }
67}
68
69impl fmt::Display for IpfwError
70{
71 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result
72 {
73 write!(f, "{}", self.message)
74 }
75}
76impl fmt::Debug for IpfwError
77{
78 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result
79 {
80 write!(f, "{}", self.message)
81 }
82}
83
84impl From<nix::Error> for IpfwError
85{
86 fn from(value: nix::Error) -> Self
87 {
88 return IpfwError::new_nix_err(value);
89 }
90}
91
92pub type IpfwResult<T> = Result<T, IpfwError>;
93
94
95#[macro_export]
96macro_rules! runtime_error
97{
98 ($($arg:tt)*) => (
99 return std::result::Result::Err(
100 $crate::runtime_exception::IpfwError::new(format!($($arg)*))
101 )
102 )
103}
104
105#[macro_export]
106macro_rules! map_runtime_error
107{
108 ($($arg:tt)*) => (
109 return $crate::runtime_exception::IpfwError::new(format!($($arg)*))
110 )
111}
112
113
114
115