Skip to main content

net_kit/
net_error.rs

1use std::fmt;
2
3use vibe_ready::VibeEngineError;
4
5/// Error type exposed by `net-kit`.
6///
7/// All internal [`VibeEngineError`]s are converted into this type so that the
8/// underlying runtime details are not leaked to third-party callers.
9#[derive(Debug, Clone)]
10pub enum NetError {
11    /// The monitor has not been started yet (call `Net::start` first).
12    NotStarted,
13    /// Failed to create the underlying runtime engine.
14    EngineCreate(String),
15    /// The runtime reported an execution error.
16    Runtime(String),
17    /// An internal lock is poisoned (a thread panicked while holding it, so the
18    /// state may be inconsistent).
19    ///
20    /// This should not happen during normal operation. Once this error is
21    /// returned, the caller is advised to call `Net::shutdown` to release
22    /// resources and, if needed, `start` again to rebuild a clean instance.
23    Lock,
24}
25
26impl NetError {
27    /// Normalize any standard-library lock-poison error (`PoisonError`) into
28    /// [`NetError::Lock`].
29    ///
30    /// Every `Mutex`/`RwLock` lock failure in the crate is converted through
31    /// this function, which avoids crash-prone `.unwrap()` calls in product
32    /// code and hands the error explicitly back to the developer.
33    pub(crate) fn from_poison<T>(_err: std::sync::PoisonError<T>) -> Self {
34        NetError::Lock
35    }
36}
37
38impl fmt::Display for NetError {
39    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40        match self {
41            NetError::NotStarted => write!(f, "network monitor is not started"),
42            NetError::EngineCreate(msg) => write!(f, "create runtime engine failed: {msg}"),
43            NetError::Runtime(msg) => write!(f, "runtime error: {msg}"),
44            NetError::Lock => write!(
45                f,
46                "internal state lock is poisoned; call shutdown and restart to recover"
47            ),
48        }
49    }
50}
51
52impl std::error::Error for NetError {}
53
54impl From<VibeEngineError> for NetError {
55    fn from(err: VibeEngineError) -> Self {
56        NetError::Runtime(err.to_string())
57    }
58}