Skip to main content

bunqueue_client/
error.rs

1use std::backtrace::Backtrace;
2
3/// Errors returned by transport and queue operations.
4#[derive(Debug, thiserror::Error)]
5pub enum Error {
6    #[error("connection error: {0}")]
7    Connection(String),
8    #[error("authentication failed: {0}")]
9    Auth(String),
10    #[error("command failed: {0}")]
11    Command(String),
12    #[error("command timed out: {0}")]
13    Timeout(String),
14    #[error("serialization error: {0}")]
15    Serialization(String),
16    #[error("connection closed by client")]
17    Closed,
18}
19
20pub type Result<T> = std::result::Result<T, Error>;
21
22impl Error {
23    pub(crate) fn is_not_found(&self) -> bool {
24        matches!(self, Self::Command(message) if message.to_ascii_lowercase().contains("not found"))
25    }
26}
27
28/// A processor failure. Mark it unrecoverable to skip retries and enter DLQ.
29#[derive(Debug)]
30pub struct ProcessError {
31    message: String,
32    unrecoverable: bool,
33    stack: Vec<String>,
34}
35
36impl ProcessError {
37    pub fn retryable(message: impl Into<String>) -> Self {
38        Self::new(message.into(), false)
39    }
40
41    pub fn unrecoverable(message: impl Into<String>) -> Self {
42        Self::new(message.into(), true)
43    }
44
45    fn new(message: String, unrecoverable: bool) -> Self {
46        let trace = Backtrace::force_capture().to_string();
47        let mut stack = vec![format!("ProcessError: {message}")];
48        stack.extend(trace.lines().map(str::to_owned));
49        Self {
50            message,
51            unrecoverable,
52            stack,
53        }
54    }
55
56    pub fn message(&self) -> &str {
57        &self.message
58    }
59
60    pub fn is_unrecoverable(&self) -> bool {
61        self.unrecoverable
62    }
63
64    pub(crate) fn stack(&self, limit: usize) -> Vec<String> {
65        self.stack.iter().take(limit).cloned().collect()
66    }
67}
68
69impl std::fmt::Display for ProcessError {
70    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
71        formatter.write_str(&self.message)
72    }
73}
74
75impl std::error::Error for ProcessError {}