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