Skip to main content

win_desktop_utils/
error.rs

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