industrial_protocols_kernel/
error.rs1use std::time::Duration;
16
17pub type Result<T> = std::result::Result<T, ProtocolError>;
18
19#[derive(Debug, thiserror::Error)]
20#[non_exhaustive]
21pub enum ProtocolError {
22 #[error("connection failed: {0}")]
23 Connection(String),
24
25 #[error("timeout: device={device}, timeout={timeout_ms}ms")]
26 Timeout { device: String, timeout_ms: u64 },
27
28 #[error("frame parse error: protocol={protocol}, reason={reason}")]
29 Parse { protocol: String, reason: String },
30
31 #[error("device error: device={device}, code={code:#04X}, message={message}")]
32 DeviceError {
33 device: String,
34 code: u16,
35 message: String,
36 },
37
38 #[error("device not found: {0}")]
39 DeviceNotFound(String),
40
41 #[error("operation unsupported: protocol={protocol}, operation={operation}")]
42 Unsupported { protocol: String, operation: String },
43
44 #[error("circuit breaker open: device={device}, retry_after={retry_after:?}")]
45 CircuitOpen {
46 device: String,
47 retry_after: Duration,
48 },
49
50 #[error("config error: {0}")]
51 Config(String),
52
53 #[error("protocol-specific error: {0}")]
54 ProtocolSpecific(#[source] Box<dyn std::error::Error + Send + Sync>),
55
56 #[error("{context}: {source}")]
57 Context {
58 context: String,
59 #[source]
60 source: Box<ProtocolError>,
61 },
62}
63
64impl ProtocolError {
65 pub fn context(self, ctx: impl Into<String>) -> Self {
66 ProtocolError::Context {
67 context: ctx.into(),
68 source: Box::new(self),
69 }
70 }
71}
72
73impl From<std::io::Error> for ProtocolError {
74 fn from(e: std::io::Error) -> Self {
75 ProtocolError::Connection(e.to_string())
76 }
77}
78
79impl From<String> for ProtocolError {
80 fn from(s: String) -> Self {
81 ProtocolError::ProtocolSpecific(Box::new(std::io::Error::other(s)))
82 }
83}
84
85impl From<&str> for ProtocolError {
86 fn from(s: &str) -> Self {
87 ProtocolError::ProtocolSpecific(Box::new(std::io::Error::other(s.to_string())))
88 }
89}