guestfs/
error.rs

1/* libguestfs Rust bindings
2 * Copyright (C) 2009-2019 Red Hat Inc.
3 *
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2 of the License, or (at your option) any later version.
8 *
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12 * Lesser General Public License for more details.
13 *
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17 */
18
19use crate::base;
20use crate::utils;
21use std::convert;
22use std::ffi;
23use std::os::raw::{c_char, c_int};
24use std::str;
25
26#[link(name = "guestfs")]
27extern "C" {
28    fn guestfs_last_error(g: *mut base::guestfs_h) -> *const c_char;
29    fn guestfs_last_errno(g: *mut base::guestfs_h) -> c_int;
30}
31
32#[derive(Debug)]
33pub struct APIError {
34    operation: &'static str,
35    message: String,
36    errno: i32,
37}
38
39#[derive(Debug)]
40pub enum Error {
41    API(APIError),
42    IllegalString(ffi::NulError),
43    Utf8Error(str::Utf8Error),
44    Create,
45}
46
47impl convert::From<ffi::NulError> for Error {
48    fn from(error: ffi::NulError) -> Self {
49        Error::IllegalString(error)
50    }
51}
52
53impl convert::From<str::Utf8Error> for Error {
54    fn from(error: str::Utf8Error) -> Self {
55        Error::Utf8Error(error)
56    }
57}
58
59impl base::Handle {
60    pub(crate) fn get_error_from_handle(&self, operation: &'static str) -> Error {
61        let c_msg = unsafe { guestfs_last_error(self.g) };
62        let message = unsafe { utils::char_ptr_to_string(c_msg).unwrap() };
63        let errno = unsafe { guestfs_last_errno(self.g) };
64        Error::API(APIError {
65            operation,
66            message,
67            errno,
68        })
69    }
70}