Skip to main content

wslplugins_rs/api/
errors.rs

1//! # Error Handling for WSL Plugins
2//!
3//! This module defines a unified error type for handling errors in WSL plugins, combining
4//! both custom plugin-specific errors and Windows system errors. It provides seamless
5//! interoperability with Windows APIs using `HRESULT`.
6
7use thiserror::Error;
8pub mod require_update_error;
9pub use require_update_error::Error as RequireUpdateError;
10use windows_core::{Error as WinError, HRESULT};
11use wslpluginapi_sys::WSL_E_PLUGIN_REQUIRES_UPDATE;
12
13/// A comprehensive error type for WSL plugins.
14///
15/// This enum encapsulates two main error categories:
16/// - Plugin-specific errors (`RequireUpdateError`).
17/// - Errors originating from Windows APIs (`WinError`).
18#[derive(Debug, Error)]
19pub enum Error {
20    /// Indicates that the current WSL version does not meet the required version.
21    #[error("Require Update Error")]
22    RequiresUpdate(#[from] RequireUpdateError),
23
24    /// Represents an error from Windows APIs.
25    #[error("Windows Error: {0}")]
26    WinError(#[from] WinError),
27}
28
29impl Error {
30    /// Retrieves the error code as an `HRESULT`.
31    ///
32    /// # Returns
33    /// The error code wrapped in an `HRESULT`.
34    #[inline]
35    pub const fn code(&self) -> HRESULT {
36        match &self {
37            Self::RequiresUpdate(_) => RequireUpdateError::WSL_E_PLUGIN_REQUIRES_UPDATE,
38            Self::WinError(error) => error.code(),
39        }
40    }
41}
42
43impl From<Error> for HRESULT {
44    /// Converts the `Error` enum into an `HRESULT` code.
45    ///
46    /// - Maps `Error::RequiresUpdate` to `WSL_E_PLUGIN_REQUIRES_UPDATE`.
47    /// - Maps `Error::WinError` to its corresponding `HRESULT` code.
48    ///
49    /// # Returns
50    /// An `HRESULT` code representing the error.
51    #[inline]
52    fn from(value: Error) -> Self {
53        match value {
54            Error::RequiresUpdate(err) => err.into(),
55            Error::WinError(err) => err.code(),
56        }
57    }
58}
59
60impl From<Error> for WinError {
61    /// Converts the `Error` enum into a `WinError`.
62    ///
63    /// - Maps `Error::RequiresUpdate` to `WSL_E_PLUGIN_REQUIRES_UPDATE`.
64    /// - Maps `Error::WinError` directly to itself.
65    ///
66    /// # Returns
67    /// A `WinError` representing the error.
68    #[inline]
69    fn from(value: Error) -> Self {
70        match value {
71            Error::RequiresUpdate { .. } => HRESULT(WSL_E_PLUGIN_REQUIRES_UPDATE).into(),
72            Error::WinError(error) => error,
73        }
74    }
75}
76
77/// A type alias for results using the custom `Error` type.
78///
79/// This alias simplifies the return type for functions that may fail, ensuring consistency
80/// across the codebase.
81pub type Result<T> = std::result::Result<T, Error>;