Skip to main content

teloxide/
error_handlers.rs

1//! Convenient error handling.
2
3use std::{convert::Infallible, fmt::Debug, future::Future, sync::Arc};
4
5use dptree::di::DependencyMap;
6use futures::future::BoxFuture;
7
8/// An asynchronous handler of an error with dependencies.
9///
10/// See [the module-level documentation for the design
11/// overview](crate::dispatching).
12pub trait ErrorHandler<E> {
13    /// Handles `error` with the dependencies available at the point of failure.
14    ///
15    /// The map may be empty. Use [`DependencyMap::try_get`] if a dependency
16    /// might not be present.
17    fn handle_error(self: Arc<Self>, error: E, deps: DependencyMap) -> BoxFuture<'static, ()>;
18}
19
20impl<E, F, Fut> ErrorHandler<E> for F
21where
22    F: Fn(E, DependencyMap) -> Fut + Send + Sync + 'static,
23    E: Send + 'static,
24    Fut: Future<Output = ()> + Send,
25{
26    fn handle_error(self: Arc<Self>, error: E, deps: DependencyMap) -> BoxFuture<'static, ()> {
27        Box::pin(async move { self(error, deps).await })
28    }
29}
30
31/// Something that can be handled by an error handler.
32///
33/// ## Examples
34/// ```
35/// use teloxide::error_handlers::OnError;
36///
37/// # #[tokio::main]
38/// # async fn main_() {
39/// // Prints nothing
40/// let ok: Result<i32, i32> = Ok(200);
41/// ok.log_on_error().await;
42///
43/// // Prints "Error: 404"
44/// let err: Result<i32, i32> = Err(404);
45/// err.log_on_error().await;
46/// # }
47/// ```
48///
49/// Use an arbitrary error handler:
50/// ```
51/// use teloxide::error_handlers::{IgnoringErrorHandler, OnError};
52///
53/// # #[tokio::main]
54/// # async fn main_() {
55/// let err: Result<i32, i32> = Err(404);
56/// err.on_error(IgnoringErrorHandler::new()).await;
57/// # }
58/// ```
59pub trait OnError<E> {
60    /// Handles errors with `eh`, passing an empty dependency map.
61    fn on_error<'a, Eh>(self, eh: Arc<Eh>) -> BoxFuture<'a, ()>
62    where
63        Self: 'a,
64        Eh: ErrorHandler<E> + Send + Sync,
65        Arc<Eh>: 'a;
66
67    /// A shortcut for `.on_error(LoggingErrorHandler::new())`.
68    fn log_on_error<'a>(self) -> BoxFuture<'a, ()>
69    where
70        Self: Sized + 'a,
71        E: Debug,
72    {
73        self.on_error(LoggingErrorHandler::new())
74    }
75}
76
77impl<T, E> OnError<E> for Result<T, E>
78where
79    T: Send,
80    E: Send,
81{
82    fn on_error<'a, Eh>(self, eh: Arc<Eh>) -> BoxFuture<'a, ()>
83    where
84        Self: 'a,
85        Eh: ErrorHandler<E> + Send + Sync,
86        Arc<Eh>: 'a,
87    {
88        Box::pin(async move {
89            if let Err(error) = self {
90                eh.handle_error(error, DependencyMap::new()).await;
91            }
92        })
93    }
94}
95
96/// A handler that silently ignores all errors.
97///
98/// ## Example
99/// ```
100/// # #[tokio::main]
101/// # async fn main_() {
102/// use dptree::di::DependencyMap;
103/// use teloxide::error_handlers::{ErrorHandler, IgnoringErrorHandler};
104///
105/// IgnoringErrorHandler::new().handle_error((), DependencyMap::new()).await;
106/// IgnoringErrorHandler::new().handle_error(404, DependencyMap::new()).await;
107/// IgnoringErrorHandler::new().handle_error("error", DependencyMap::new()).await;
108/// # }
109/// ```
110#[derive(Clone, Copy)]
111pub struct IgnoringErrorHandler;
112
113impl IgnoringErrorHandler {
114    #[must_use]
115    pub fn new() -> Arc<Self> {
116        Arc::new(Self)
117    }
118}
119
120impl<E> ErrorHandler<E> for IgnoringErrorHandler {
121    fn handle_error(self: Arc<Self>, _: E, _: DependencyMap) -> BoxFuture<'static, ()> {
122        Box::pin(async {})
123    }
124}
125
126/// A handler that silently ignores all errors that can never happen (e.g.:
127/// [`!`] or [`Infallible`]).
128///
129/// ## Examples
130/// ```
131/// # #[tokio::main]
132/// # async fn main_() {
133/// use std::convert::{Infallible, TryInto};
134///
135/// use dptree::di::DependencyMap;
136/// use teloxide::error_handlers::{ErrorHandler, IgnoringErrorHandlerSafe};
137///
138/// let result: Result<String, Infallible> = "str".try_into();
139/// match result {
140///     Ok(string) => println!("{}", string),
141///     Err(inf) => IgnoringErrorHandlerSafe::new().handle_error(inf, DependencyMap::new()).await,
142/// }
143///
144/// IgnoringErrorHandlerSafe::new().handle_error(return, DependencyMap::new()).await;
145/// // return type of `return` is `!` (aka never)
146/// # }
147/// ```
148///
149/// ```compile_fail
150/// use teloxide::{dptree::di::DependencyMap, error_handlers::{ErrorHandler, IgnoringErrorHandlerSafe}};
151///
152/// IgnoringErrorHandlerSafe::new().handle_error(0, DependencyMap::new());
153/// ```
154///
155/// [`!`]: https://doc.rust-lang.org/std/primitive.never.html
156/// [`Infallible`]: std::convert::Infallible
157#[derive(Clone, Copy)]
158pub struct IgnoringErrorHandlerSafe;
159
160impl IgnoringErrorHandlerSafe {
161    #[must_use]
162    pub fn new() -> Arc<Self> {
163        Arc::new(Self)
164    }
165}
166
167#[allow(unreachable_code)]
168impl ErrorHandler<Infallible> for IgnoringErrorHandlerSafe {
169    fn handle_error(self: Arc<Self>, _: Infallible, _: DependencyMap) -> BoxFuture<'static, ()> {
170        Box::pin(async {})
171    }
172}
173
174/// A handler that log all errors passed into it.
175///
176/// ## Example
177/// ```
178/// # #[tokio::main]
179/// # async fn main_() {
180/// use dptree::di::DependencyMap;
181/// use teloxide::error_handlers::{ErrorHandler, LoggingErrorHandler};
182///
183/// LoggingErrorHandler::new().handle_error((), DependencyMap::new()).await;
184/// LoggingErrorHandler::with_custom_text("Omg1").handle_error(404, DependencyMap::new()).await;
185/// LoggingErrorHandler::with_custom_text("Omg2")
186///     .handle_error("Invalid data type!", DependencyMap::new())
187///     .await;
188/// # }
189/// ```
190pub struct LoggingErrorHandler {
191    text: String,
192}
193
194impl LoggingErrorHandler {
195    /// Creates `LoggingErrorHandler` with a meta text before a log.
196    ///
197    /// The logs will be printed in this format: `{text}: {:?}`.
198    #[must_use]
199    pub fn with_custom_text<T>(text: T) -> Arc<Self>
200    where
201        T: Into<String>,
202    {
203        Arc::new(Self { text: text.into() })
204    }
205
206    /// A shortcut for
207    /// `LoggingErrorHandler::with_custom_text("Error".to_owned())`.
208    #[must_use]
209    pub fn new() -> Arc<Self> {
210        Self::with_custom_text("Error".to_owned())
211    }
212}
213
214impl<E> ErrorHandler<E> for LoggingErrorHandler
215where
216    E: Debug,
217{
218    fn handle_error(self: Arc<Self>, error: E, _: DependencyMap) -> BoxFuture<'static, ()> {
219        log::error!("{text}: {:?}", error, text = self.text);
220        Box::pin(async {})
221    }
222}