Skip to main content

win_desktop_utils/
error.rs

1/// Error type for `win-desktop-utils`.
2#[derive(Debug)]
3pub enum Error {
4    /// The requested operation is not implemented on the current platform or in the current crate version.
5    Unsupported(&'static str),
6    /// The caller supplied invalid input.
7    InvalidInput(&'static str),
8    /// A path was required to be absolute but was not.
9    PathNotAbsolute,
10    /// A required path does not exist.
11    PathDoesNotExist,
12    /// An underlying I/O operation failed.
13    Io(std::io::Error),
14    /// A Windows API call failed.
15    WindowsApi {
16        /// Short label describing the failing API call.
17        context: &'static str,
18        /// Raw Windows error or return code when available.
19        code: i32,
20    },
21}
22
23/// Convenient result alias for this crate.
24pub type Result<T> = std::result::Result<T, Error>;
25
26impl std::fmt::Display for Error {
27    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
28        match self {
29            Self::Unsupported(msg) => write!(f, "unsupported operation: {msg}"),
30            Self::InvalidInput(msg) => write!(f, "invalid input: {msg}"),
31            Self::PathNotAbsolute => write!(f, "path must be absolute"),
32            Self::PathDoesNotExist => write!(f, "path does not exist"),
33            Self::Io(err) => write!(f, "I/O error: {err}"),
34            Self::WindowsApi { context, code } => {
35                write!(f, "Windows API error in {context} (code {code})")
36            }
37        }
38    }
39}
40
41impl std::error::Error for Error {
42    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
43        match self {
44            Self::Io(err) => Some(err),
45            _ => None,
46        }
47    }
48}
49
50impl From<std::io::Error> for Error {
51    fn from(value: std::io::Error) -> Self {
52        Self::Io(value)
53    }
54}