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::other(format!("{}, source: {:?}", message, source)),
65 None => io::Error::other(message),
66 }
67 }
68 Error::Unexpected { message, source } => {
69 let message = format!("Unexpected error: {}", message);
70 match source {
71 Some(source) => io::Error::other(format!("{}, source: {:?}", message, source)),
72 None => io::Error::other(message),
73 }
74 }
75 }
76 }
77}
78
79pub type Result<T, E = Error> = std::result::Result<T, E>;
81
82pub fn new_vhost_user_fs_error(message: &str, source: Option<AnyError>) -> Error {
83 Error::VhostUserFsError {
84 message: message.to_string(),
85 source,
86 }
87}
88
89pub fn new_unexpected_error(message: &str, source: Option<AnyError>) -> Error {
90 Error::Unexpected {
91 message: message.to_string(),
92 source,
93 }
94}