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    /// An underlying I/O operation failed.
9    Io(std::io::Error),
10    /// A Windows API call failed.
11    WindowsApi {
12        /// Short label describing the failing API call.
13        context: &'static str,
14        /// Raw Windows error or return code when available.
15        code: i32,
16    },
17}
18
19/// Convenient result alias for this crate.
20pub type Result<T> = std::result::Result<T, Error>;
21
22impl std::fmt::Display for Error {
23    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
24        match self {
25            Self::Unsupported(msg) => write!(f, "unsupported operation: {msg}"),
26            Self::InvalidInput(msg) => write!(f, "invalid input: {msg}"),
27            Self::Io(err) => write!(f, "I/O error: {err}"),
28            Self::WindowsApi { context, code } => {
29                write!(f, "Windows API error in {context} (code {code})")
30            }
31        }
32    }
33}
34
35impl std::error::Error for Error {
36    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
37        match self {
38            Self::Io(err) => Some(err),
39            _ => None,
40        }
41    }
42}
43
44impl From<std::io::Error> for Error {
45    fn from(value: std::io::Error) -> Self {
46        Self::Io(value)
47    }
48}