Skip to main content

opc_da_client/opc_da/
errors.rs

1use thiserror::Error;
2use windows::core::HRESULT;
3
4/// Result type alias for OPC DA operations.
5pub type OpcResult<T> = Result<T, OpcError>;
6
7/// Centralized error enum for the OPC DA client.
8#[derive(Debug, Error)]
9#[non_exhaustive]
10pub enum OpcError {
11    /// Standard Windows COM/DCOM error.
12    ///
13    /// This variant wraps a [`windows::core::Error`] and provides a friendly
14    /// hint for common OPC-related HRESULT codes.
15    #[error("COM error: {source} ({})", friendly_hresult_hint(.source.code()).unwrap_or("No hint available"))]
16    Com {
17        #[from]
18        source: windows::core::Error,
19    },
20
21    /// Connection-related errors (e.g., host unreachable, resolution failure).
22    #[error("Connection failed: {0}")]
23    Connection(String),
24
25    /// Server-specific errors reported via OPC status codes.
26    #[error("Server error: {0} (0x{1:08X})")]
27    Server(String, u32),
28
29    /// Errors during data type conversion or VARIANT processing.
30    #[error("Data conversion failed: {0}")]
31    Conversion(String),
32
33    /// Operation attempted in an invalid state (e.g., group already exists).
34    #[error("Invalid state: {0}")]
35    InvalidState(String),
36
37    /// Feature not implemented or supported by the target OPC server.
38    #[error("Not implemented: {0}")]
39    NotImplemented(String),
40
41    /// Catch-all for unexpected internal failures.
42    #[error("Internal error: {0}")]
43    Internal(String),
44}
45
46impl From<anyhow::Error> for OpcError {
47    fn from(err: anyhow::Error) -> Self {
48        Self::Internal(err.to_string())
49    }
50}
51
52impl From<tokio::task::JoinError> for OpcError {
53    fn from(err: tokio::task::JoinError) -> Self {
54        Self::Internal(format!("Async task join failed: {err}"))
55    }
56}
57
58impl From<std::num::TryFromIntError> for OpcError {
59    fn from(err: std::num::TryFromIntError) -> Self {
60        OpcError::Conversion(format!("Integer conversion error: {err}"))
61    }
62}
63
64/// Helper to format HRESULT with friendly hints.
65pub fn format_hresult(hr: HRESULT) -> String {
66    let hex = format!("0x{:08X}", hr.0 as u32);
67    match friendly_hresult_hint(hr) {
68        Some(hint) => format!("{hex}: {hint}"),
69        None => hex,
70    }
71}
72
73/// Maps known COM/DCOM error codes to actionable user hints.
74pub fn friendly_hresult_hint(hr: HRESULT) -> Option<&'static str> {
75    match hr.0 as u32 {
76        0x80040112 => Some("Server license does not permit OPC client connections"),
77        0x80080005 => Some("Server process failed to start — check if it is installed and running"),
78        0x80070005 => {
79            Some("Access denied — DCOM launch/activation permissions not configured for this user")
80        }
81        0x800706BA => {
82            Some("RPC server unavailable — the target host may be offline or blocking RPC")
83        }
84        0x800706F4 => Some("COM marshalling error — try restarting the OPC server"),
85        0x80040154 => Some("Server is not registered on this machine"),
86        0x80004003 => Some("Invalid pointer (E_POINTER)"),
87        0xC0040004 => Some("Server rejected write — the item may be read-only (OPC_E_BADRIGHTS)"),
88        0xC0040006 => {
89            Some("Data type mismatch — server cannot convert the written value (OPC_E_BADTYPE)")
90        }
91        0xC0040007 => Some("Item ID not found in server address space (OPC_E_UNKNOWNITEMID)"),
92        0xC0040008 => Some("Item ID syntax is invalid for this server (OPC_E_INVALIDITEMID)"),
93        _ => None,
94    }
95}
96
97/// Maps an [`OpcError`] to a friendly COM hint if it is a COM error.
98pub fn friendly_com_hint(error: &OpcError) -> Option<&'static str> {
99    match error {
100        OpcError::Com { source: e } => friendly_hresult_hint(e.code()),
101        _ => None,
102    }
103}
104
105/// Emits a structured `tracing::error!` event with machine-parseable fields.
106///
107/// Extracts the HRESULT code and friendly hint from an [`OpcError`],
108/// and logs them as named fields for aggregation by log analysis tools.
109///
110/// # Arguments
111/// * `error` - The OPC error to log
112/// * `operation` - Name of the operation that failed (e.g., "read_tag_values")
113pub fn log_opc_error(error: &OpcError, operation: &str) {
114    let hresult = match error {
115        OpcError::Com { source: e } => Some(format!("0x{:08X}", e.code().0 as u32)),
116        _ => None,
117    };
118    let hint = friendly_com_hint(error);
119    let chain = format!("{error:#}");
120
121    tracing::error!(
122        operation = %operation,
123        hresult = hresult.as_deref().unwrap_or("N/A"),
124        hint = hint.unwrap_or("none"),
125        chain = %chain,
126        "OPC operation failed"
127    );
128}