-
Notifications
You must be signed in to change notification settings - Fork 1
/
error.rs
105 lines (93 loc) · 2.62 KB
/
error.rs
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see
* <http://www.gnu.org/licenses/>.
*
* Sahid Orentino Ferdjaoui <sahid.ferdjaoui@redhat.com>
*/
extern crate libc;
use std::error::Error as StdError;
use std::fmt::{Display, Result as FmtResult, Formatter};
pub mod sys {
extern crate libc;
#[allow(non_camel_case_types)]
#[repr(C)]
pub struct virError {
pub code: libc::c_int,
pub domain: libc::c_int,
pub message: *mut libc::c_char,
pub level: libc::c_uint,
}
#[allow(non_camel_case_types)]
pub type virErrorPtr = *mut virError;
}
#[link(name = "virt")]
extern "C" {
fn virGetLastError() -> sys::virErrorPtr;
}
#[derive(Debug, PartialEq)]
pub enum ErrorLevel {
NONE = 0,
/// A simple warning.
WARNING = 1,
/// An error.
ERROR = 2,
}
impl ::std::convert::From<u32> for ErrorLevel {
fn from(value: u32) -> ErrorLevel {
match value {
0 => ErrorLevel::NONE,
1 => ErrorLevel::WARNING,
2 => ErrorLevel::ERROR,
unknow => panic!("Invalid ErrorLevel provided: {:?}", unknow)
}
}
}
/// Error handling
///
/// See: http://libvirt.org/html/libvirt-virterror.html
#[derive(Debug, PartialEq)]
pub struct Error {
pub code: i32,
pub domain: i32,
pub message: String,
pub level: ErrorLevel,
}
impl Error {
pub fn new() -> Error {
unsafe {
let ptr: sys::virErrorPtr = virGetLastError();
Error {
code: (*ptr).code,
domain: (*ptr).domain,
message: c_chars_to_string!((*ptr).message, nofree),
level: ErrorLevel::from((*ptr).level),
}
}
}
}
impl StdError for Error {
fn description(&self) -> &str {
self.message.as_str()
}
}
impl Display for Error {
fn fmt(&self, f: &mut Formatter) -> FmtResult {
write!(f,
"{:?}: code: {} domain: {} - {}",
self.level,
self.code,
self.domain,
self.message)
}
}