virtiofs_opendal/
error.rs1use std::ffi::CStr;
19use std::io;
20
21use anyhow::Error as AnyError;
22use snafu::prelude::Snafu;
23
24#[derive(Debug, Snafu)]
26#[non_exhaustive]
27pub enum Error {
28 #[snafu(display("Vhost user fs error: {}, source: {:?}", message, source))]
29 VhostUserFsError {
30 message: String,
31 #[snafu(source(false))]
32 source: Option<AnyError>,
33 },
34 #[snafu(display("Unexpected error: {}, source: {:?}", message, source))]
35 Unexpected {
36 message: String,
37 #[snafu(source(false))]
38 source: Option<AnyError>,
39 },
40}
41
42impl From<libc::c_int> for Error {
43 fn from(errno: libc::c_int) -> Error {
44 let err_str = unsafe { libc::strerror(errno) };
45 let message = if err_str.is_null() {
46 format!("errno: {}", errno)
47 } else {
48 let c_str = unsafe { CStr::from_ptr(err_str) };
49 c_str.to_string_lossy().into_owned()
50 };
51 Error::VhostUserFsError {
52 message,
53 source: None,
54 }
55 }
56}
57
58impl From<Error> for io::Error {
59 fn from(error: Error) -> io::Error {
60 match error {
61 Error::VhostUserFsError { message, source } => {
62 let message = format!("Vhost user fs error: {}", message);
63 match source {
64 Some(source) => io::Error::new(
65 io::ErrorKind::Other,
66 format!("{}, source: {:?}", message, source),
67 ),
68 None => io::Error::new(io::ErrorKind::Other, message),
69 }
70 }
71 Error::Unexpected { message, source } => {
72 let message = format!("Unexpected error: {}", message);
73 match source {
74 Some(source) => io::Error::new(
75 io::ErrorKind::Other,
76 format!("{}, source: {:?}", message, source),
77 ),
78 None => io::Error::new(io::ErrorKind::Other, message),
79 }
80 }
81 }
82 }
83}
84
85pub type Result<T, E = Error> = std::result::Result<T, E>;
87
88pub fn new_vhost_user_fs_error(message: &str, source: Option<AnyError>) -> Error {
89 Error::VhostUserFsError {
90 message: message.to_string(),
91 source,
92 }
93}
94
95pub fn new_unexpected_error(message: &str, source: Option<AnyError>) -> Error {
96 Error::Unexpected {
97 message: message.to_string(),
98 source,
99 }
100}