Skip to main content

apalis_core/
error.rs

1#![allow(deprecated)]
2// TODO: @geofmureithi: Remove the deprecated error types and their usage in the future. The `DeferredError` type is no longer necessary, and the `RetryAfterError` can be handled differently to indicate that a task should be retried later.
3use std::{
4    error::Error as StdError,
5    marker::PhantomData,
6    pin::Pin,
7    task::{Context, Poll},
8    time::Duration,
9};
10use thiserror::Error;
11use tower_service::Service;
12
13/// Convenience type alias
14pub type BoxDynError = Box<dyn StdError + 'static + Send + Sync>;
15/// Execution should be aborted
16/// This signifies that the task should not be retried
17#[derive(Error, Debug)]
18#[error("AbortError: {source}")]
19pub struct AbortError {
20    #[source]
21    source: BoxDynError,
22}
23impl AbortError {
24    /// Create a new abort error
25    pub fn new<E: Into<BoxDynError>>(err: E) -> Self {
26        Self { source: err.into() }
27    }
28}
29
30/// Execution should be retried after a specific duration
31/// This increases the attempts
32#[derive(Error, Debug)]
33#[error("RetryAfterError: {source}, duration: {duration:?}")]
34pub struct RetryAfterError {
35    #[source]
36    source: BoxDynError,
37    duration: Duration,
38}
39
40impl RetryAfterError {
41    /// Create a new retry after error
42    pub fn new<E: Into<BoxDynError>>(err: E, duration: Duration) -> Self {
43        Self {
44            source: err.into(),
45            duration,
46        }
47    }
48
49    /// Get the duration after which the task should be retried
50    #[must_use]
51    pub fn get_duration(&self) -> Duration {
52        self.duration
53    }
54}
55
56/// Execution should be deferred, will be retried instantly
57#[deprecated(
58    since = "1.1.1",
59    note = "This error type is deprecated and will be removed in a future release. Returning a `BoxDynError` or a custom error directly is now the preferred way to indicate that a task should be retried."
60)]
61#[allow(deprecated)]
62#[derive(Error, Debug)]
63#[error("DeferredError: {source}")]
64pub struct DeferredError {
65    #[source]
66    source: BoxDynError,
67}
68
69#[allow(deprecated)]
70impl DeferredError {
71    /// Compose a new Deferred error
72    pub fn new<E: Into<BoxDynError>>(source: E) -> Self {
73        Self {
74            source: source.into(),
75        }
76    }
77}
78
79/// Possible errors that can occur when running a worker.
80#[non_exhaustive]
81#[derive(Error, Debug)]
82pub enum WorkerError {
83    /// An error occurred while polling.
84    #[error("Failed to poll backend: {0}")]
85    BackendError(BoxDynError),
86    /// An error occurred while trying to change the state of the worker.
87    #[error("Failed to handle the new state: {0}")]
88    StateError(#[from] WorkerStateError),
89    /// A worker panicked and the panic was caught.
90    #[error("Worker panicked: {0}")]
91    PanicError(String),
92    /// An error occurred while handling io
93    #[error("IO error: {0}")]
94    IoError(#[from] std::io::Error),
95}
96
97/// Errors related to worker state transitions
98#[derive(Error, Debug)]
99#[non_exhaustive]
100pub enum WorkerStateError {
101    /// Worker not started
102    #[error("Worker not started, did you forget to call worker.start()")]
103    NotStarted,
104    /// Worker already started
105    #[error("Worker already started")]
106    AlreadyStarted,
107    /// Worker is not running
108    #[error("Worker is not running")]
109    NotRunning,
110    /// Worker is not paused
111    #[error("Worker is not paused")]
112    NotPaused,
113    /// Worker is shutting down
114    #[error("Worker is shutting down")]
115    ShuttingDown,
116    /// Invalid state provided
117    #[error("Worker provided with invalid state {0}")]
118    InvalidState(String),
119}
120
121/// A Tower layer for handling and converting service errors into a `BoxDynError`.
122///
123/// The service's error type must implement `std::error::Error`, allowing for flexible
124/// error handling, especially when dealing with trait objects or complex error chains.
125#[derive(Clone, Debug)]
126pub struct ErrorHandlingLayer {
127    _p: PhantomData<()>,
128}
129
130impl ErrorHandlingLayer {
131    /// Create a new ErrorHandlingLayer
132    #[must_use]
133    pub fn new() -> Self {
134        Self { _p: PhantomData }
135    }
136}
137
138impl Default for ErrorHandlingLayer {
139    fn default() -> Self {
140        Self::new()
141    }
142}
143
144impl<S> tower_layer::Layer<S> for ErrorHandlingLayer {
145    type Service = ErrorHandlingService<S>;
146
147    fn layer(&self, service: S) -> Self::Service {
148        ErrorHandlingService { service }
149    }
150}
151
152/// The underlying service
153#[derive(Clone, Debug)]
154pub struct ErrorHandlingService<S> {
155    service: S,
156}
157
158impl<S, Request> Service<Request> for ErrorHandlingService<S>
159where
160    S: Service<Request>,
161    S::Error: std::error::Error + Send + Sync + 'static,
162    S::Future: Send + 'static,
163{
164    type Response = S::Response;
165    type Error = BoxDynError;
166    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
167
168    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
169        self.service.poll_ready(cx).map_err(|e| {
170            let boxed_error: BoxDynError = e.into();
171            boxed_error
172        })
173    }
174
175    fn call(&mut self, req: Request) -> Self::Future {
176        let fut = self.service.call(req);
177
178        Box::pin(async move {
179            fut.await.map_err(|e| {
180                let boxed_error: BoxDynError = e.into();
181                boxed_error
182            })
183        })
184    }
185}