mikrotik_rs/
error.rs

1use std::fmt;
2use std::io;
3
4use crate::protocol::word::WordCategory;
5use crate::protocol::CommandResponse;
6use crate::protocol::TrapResponse;
7
8/// Result type alias for MikroTik device operations
9pub type DeviceResult<T> = Result<T, DeviceError>;
10
11/// Custom error type for MikroTik device operations
12#[derive(Debug, Clone)]
13pub enum DeviceError {
14    /// Connection related errors (TCP, network issues)
15    Connection(io::ErrorKind),
16    /// Authentication failure
17    Authentication {
18        /// The response received from the device
19        response: TrapResponse,
20    },
21    /// Channel errors
22    Channel {
23        /// Error message
24        message: String,
25    },
26    /// Unexpected sequence of responses received
27    ResponseSequence {
28        /// The response received from the device
29        received: CommandResponse,
30        /// The values accepted as valid responses
31        expected: Vec<WordCategory>,
32    },
33}
34
35impl fmt::Display for DeviceError {
36    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37        match self {
38            DeviceError::Connection(err) => write!(f, "Connection error: {}", err),
39            DeviceError::Authentication { response } => {
40                write!(f, "Authentication failed: {}", response)
41            }
42            DeviceError::Channel { message } => write!(f, "Channel error: {}", message),
43            DeviceError::ResponseSequence { received, expected } => write!(
44                f,
45                "Unexpected response sequence: received {:?}, expected {:?}",
46                received, expected
47            ),
48        }
49    }
50}
51
52impl From<io::Error> for DeviceError {
53    fn from(error: io::Error) -> Self {
54        DeviceError::Connection(error.kind())
55    }
56}
57
58impl<T> From<tokio::sync::mpsc::error::SendError<T>> for DeviceError {
59    fn from(_: tokio::sync::mpsc::error::SendError<T>) -> Self {
60        DeviceError::Channel {
61            message: "Failed to send message through channel".to_string(),
62        }
63    }
64}
65
66impl std::error::Error for DeviceError {}