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