Skip to main content

systemconfiguration/
error.rs

1use std::{error::Error, fmt};
2
3use crate::{bridge, ffi};
4
5/// Result alias used by SystemConfiguration wrapper APIs.
6pub type Result<T> = std::result::Result<T, SystemConfigurationError>;
7
8#[derive(Clone, Debug, Eq, PartialEq)]
9/// Wraps SystemConfiguration framework failures.
10pub struct SystemConfigurationError {
11    /// Wraps the failing SystemConfiguration entry point.
12    pub function: &'static str,
13    /// Wraps the SystemConfiguration error code.
14    pub code: i32,
15    /// Wraps the SystemConfiguration error message.
16    pub message: String,
17}
18
19impl SystemConfigurationError {
20    pub(crate) fn new(function: &'static str, code: i32, message: impl Into<String>) -> Self {
21        Self {
22            function,
23            code,
24            message: message.into(),
25        }
26    }
27
28    pub(crate) fn last(function: &'static str) -> Self {
29        let code = unsafe { ffi::core::sc_last_error_code() };
30        let message = bridge::take_optional_string(unsafe { ffi::core::sc_last_error_message() })
31            .unwrap_or_else(|| format!("SystemConfiguration returned error code {code}"));
32        Self::new(function, code, message)
33    }
34
35    pub(crate) fn null(function: &'static str, message: impl Into<String>) -> Self {
36        Self::new(function, 0, message)
37    }
38}
39
40impl fmt::Display for SystemConfigurationError {
41    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
42        write!(
43            f,
44            "{} failed (code {}): {}",
45            self.function, self.code, self.message
46        )
47    }
48}
49
50impl Error for SystemConfigurationError {}