tinylfu_cached/cache/command/
error.rs

1use std::error::Error;
2use std::fmt::{Debug, Display, Formatter};
3
4const SHUTDOWN_MESSAGE: &str = "could not accept the command for execution, probably the cache is being shutdown.";
5
6/// The execution of every write operation is returned a [`crate::cache::command::command_executor::CommandSendResult`].
7///
8/// `CommandSendResult` wraps `CommandSendError` that is encountered when there is an error in sending a command to `crate::cache::command::command_executor::CommandExecutor`.
9///
10/// `CommandSendError` is also returned to the clients if an attempt is made to perform any operation say `put`, `delete`, while the cache is being shutdown.
11pub struct CommandSendError {
12    command_description: String,
13}
14
15impl CommandSendError {
16    pub(crate) fn new(command_description: String) -> Self {
17        CommandSendError {
18            command_description
19        }
20    }
21
22    pub(crate) fn shutdown() -> Self {
23        CommandSendError {
24            command_description: SHUTDOWN_MESSAGE.to_string()
25        }
26    }
27}
28
29/// Display implementation for `CommandSendError`. Currently, both `Display` and `Debug` return the same message.
30impl Display for CommandSendError {
31    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
32        write!(
33            formatter,
34            "{} Command description: {}",
35            SHUTDOWN_MESSAGE,
36            self.command_description
37        )
38    }
39}
40
41/// Debug implementation for `CommandSendError`. Currently, both `Display` and `Debug` return the same message.
42impl Debug for CommandSendError {
43    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
44        write!(
45            formatter,
46            "{} Command description: {}",
47            SHUTDOWN_MESSAGE,
48            self.command_description
49        )
50    }
51}
52
53/// Error implementation for `CommandSendError`.
54impl Error for CommandSendError {}
55
56#[cfg(test)]
57mod tests {
58    use crate::cache::command::error::CommandSendError;
59
60    #[test]
61    fn command_send_error_display() {
62        let error = CommandSendError::new("put".to_string());
63        assert_eq!(
64            format!("{}", error),
65            "could not accept the command for execution, probably the cache is being shutdown. Command description: put",
66        );
67    }
68
69    #[test]
70    fn command_send_error_debug() {
71        let error = CommandSendError::new("put".to_string());
72        assert_eq!(
73            format!("{:?}", error),
74            "could not accept the command for execution, probably the cache is being shutdown. Command description: put",
75        );
76    }
77}