redis_module/
rediserror.rs
1use crate::context::call_reply::{ErrorCallReply, ErrorReply};
2pub use crate::raw;
3use std::ffi::CStr;
4use std::fmt;
5
6#[derive(Debug)]
7pub enum RedisError {
8 WrongArity,
9 Str(&'static str),
10 String(String),
11 WrongType,
12}
13
14impl<'root> From<ErrorCallReply<'root>> for RedisError {
15 fn from(err: ErrorCallReply<'root>) -> Self {
16 RedisError::String(
17 err.to_utf8_string()
18 .unwrap_or("can not convert error into String".into()),
19 )
20 }
21}
22
23impl<'root> From<ErrorReply<'root>> for RedisError {
24 fn from(err: ErrorReply<'root>) -> Self {
25 RedisError::String(
26 err.to_utf8_string()
27 .unwrap_or("can not convert error into String".into()),
28 )
29 }
30}
31
32impl RedisError {
33 #[must_use]
34 pub const fn nonexistent_key() -> Self {
35 Self::Str("ERR could not perform this operation on a key that doesn't exist")
36 }
37
38 #[must_use]
39 pub const fn short_read() -> Self {
40 Self::Str("ERR short read or OOM loading DB")
41 }
42}
43
44impl<T: std::error::Error> From<T> for RedisError {
45 fn from(e: T) -> Self {
46 Self::String(format!("ERR {e}"))
47 }
48}
49
50impl fmt::Display for RedisError {
51 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
52 let d = match self {
53 Self::WrongArity => "Wrong Arity",
54 Self::WrongType => std::str::from_utf8(
58 CStr::from_bytes_with_nul(raw::REDISMODULE_ERRORMSG_WRONGTYPE)
59 .unwrap()
60 .to_bytes(),
61 )
62 .unwrap(),
63 Self::Str(s) => s,
64 Self::String(s) => s.as_str(),
65 };
66
67 write!(f, "{d}")
68 }
69}