Skip to main content

aws_iot_device_sdk_rust/
error.rs

1use rumqttc::{ClientError, ConnectionError};
2use std::fmt;
3use std::fmt::Display;
4
5#[derive(Debug)]
6pub enum AWSIoTError {
7    /// Error establishing or maintaining the MQTT connection.
8    AWSConnectionError(Box<ConnectionError>),
9    /// Error performing an MQTT client operation (subscribe, publish, etc).
10    MQTTClientError(ClientError),
11    /// Error reading certificate or key files.
12    IoError(std::io::Error),
13    /// A mutex was poisoned (sync client only).
14    MutexError(String),
15    /// The private key could not be parsed or normalized.
16    KeyNormalizationError(String),
17}
18
19impl Display for AWSIoTError {
20    fn fmt(&self, f: &mut fmt::Formatter) -> std::fmt::Result {
21        match self {
22            AWSIoTError::AWSConnectionError(err) => {
23                write!(f, "Problem connecting to AWS: {err}")
24            }
25            AWSIoTError::MQTTClientError(err) => {
26                write!(f, "MQTT client error: {err}")
27            }
28            AWSIoTError::IoError(err) => write!(f, "Problem reading file: {err}"),
29            AWSIoTError::MutexError(msg) => write!(f, "Mutex poisoned: {msg}"),
30            AWSIoTError::KeyNormalizationError(msg) => {
31                write!(f, "Key normalization failed: {msg}")
32            }
33        }
34    }
35}
36
37impl std::error::Error for AWSIoTError {
38    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
39        match self {
40            AWSIoTError::AWSConnectionError(err) => Some(err),
41            AWSIoTError::MQTTClientError(err) => Some(err),
42            AWSIoTError::IoError(err) => Some(err),
43            AWSIoTError::MutexError(_) => None,
44            AWSIoTError::KeyNormalizationError(_) => None,
45        }
46    }
47}
48
49impl From<std::io::Error> for AWSIoTError {
50    fn from(err: std::io::Error) -> AWSIoTError {
51        AWSIoTError::IoError(err)
52    }
53}
54
55impl From<ConnectionError> for AWSIoTError {
56    fn from(err: ConnectionError) -> AWSIoTError {
57        AWSIoTError::AWSConnectionError(Box::new(err))
58    }
59}
60
61impl From<ClientError> for AWSIoTError {
62    fn from(err: ClientError) -> AWSIoTError {
63        AWSIoTError::MQTTClientError(err)
64    }
65}
66
67impl<T> From<std::sync::PoisonError<T>> for AWSIoTError {
68    fn from(err: std::sync::PoisonError<T>) -> AWSIoTError {
69        AWSIoTError::MutexError(err.to_string())
70    }
71}