Skip to main content

ntex_service/
map_err.rs

1use std::{fmt, marker::PhantomData};
2
3use super::{BindCtx, Ctx, Service, ServiceFactory, util};
4
5/// Transforms call and readiness errors with a synchronous function.
6///
7/// Created by [`Service::map_err`] and [`crate::ServiceChain::map_err`].
8/// The function receives an inner error and returns the new error value.
9/// Successful responses are returned unchanged without invoking the function.
10/// Request and state types are also unchanged.
11///
12/// This is useful for giving composed services a common error type. It does
13/// not recover errors into responses; use [`crate::ServiceChain::then`] for
14/// call-result recovery.
15///
16/// Binding and shutdown are forwarded to the inner service. Readiness is
17/// forwarded with the same error conversion as calls. Mapping preserves the
18/// inner service's readiness identity without adding an independent cache or
19/// an extra readiness check at call time. An explicit [`crate::ready()`]
20/// wrapper retains its own readiness behavior.
21///
22/// Cloning clones both the inner service and mapping function. Whether their
23/// state is shared depends on their clone implementations.
24///
25/// # Example
26///
27/// ```
28/// use ntex_service::{Service, fn_service};
29///
30/// # async fn example() {
31/// let pipeline = fn_service(async |req: u32| {
32///     if req == 0 { Err("zero is not allowed") } else { Ok(req) }
33/// })
34/// .map_err(|error| format!("request failed: {error}"))
35/// .pipeline(());
36///
37/// assert_eq!(pipeline.call(1).await, Ok(1));
38/// assert_eq!(
39///     pipeline.call(0).await,
40///     Err(String::from("request failed: zero is not allowed")),
41/// );
42/// # }
43/// ```
44pub struct MapErr<F, S, E> {
45    f: F,
46    svc: S,
47    e: PhantomData<E>,
48}
49
50impl<F, S, E> MapErr<F, S, E> {
51    /// Creates a new `MapErr` service.
52    pub(crate) fn new<St, Req>(f: F, svc: S) -> Self
53    where
54        S: Service<St, Req>,
55        F: Fn(S::Error) -> E,
56    {
57        Self {
58            f,
59            svc,
60            e: PhantomData,
61        }
62    }
63}
64
65impl<F, S, E> Clone for MapErr<F, S, E>
66where
67    F: Clone,
68    S: Clone,
69{
70    #[inline]
71    fn clone(&self) -> Self {
72        MapErr {
73            f: self.f.clone(),
74            svc: self.svc.clone(),
75            e: PhantomData,
76        }
77    }
78}
79
80impl<F, S, E> fmt::Debug for MapErr<F, S, E>
81where
82    S: fmt::Debug,
83{
84    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
85        f.debug_struct("MapErr")
86            .field("svc", &self.svc)
87            .field("map", &std::any::type_name::<F>())
88            .finish()
89    }
90}
91
92impl<F, S, St, Req, E> Service<St, Req> for MapErr<F, S, E>
93where
94    S: Service<St, Req>,
95    F: Fn(S::Error) -> E,
96{
97    type Res = S::Res;
98    type Error = E;
99
100    #[inline]
101    fn bind(&self, ctx: BindCtx<'_>) {
102        ctx.bind(&self.svc);
103    }
104
105    #[inline]
106    fn call(&self, req: Req, ctx: Ctx<'_, Self, St>) -> impl Future<Output = Result<S::Res, E>> {
107        util::map_output(self.svc.call(req, ctx.cast()), |res| res.map_err(&self.f))
108    }
109
110    #[inline]
111    fn ready(&self, ctx: Ctx<'_, Self, St>) -> impl Future<Output = Result<(), E>> {
112        util::map_output(self.svc.ready(ctx.cast()), |res| res.map_err(&self.f))
113    }
114
115    #[inline]
116    fn shutdown(&self, ctx: Ctx<'_, Self, St>) -> impl Future<Output = ()> {
117        self.svc.shutdown(ctx.cast())
118    }
119}
120
121/// Maps call and readiness errors from each service created by an inner factory.
122///
123/// Created by [`ServiceFactory::map_err`] and
124/// [`crate::ServiceChainFactory::map_err`]. Creation forwards the supplied state
125/// to the inner factory. On success, the new service is wrapped in [`MapErr`]
126/// with a clone of the mapping function.
127///
128/// Initialization errors are returned unchanged, without cloning or invoking
129/// the function. Use [`ServiceFactory::map_init_err`] to transform those
130/// errors. Request, response, and state types remain unchanged.
131///
132/// Created services use the lifecycle and readiness behavior described in
133/// [`MapErr`]. Cloning clones the inner factory and mapping function without
134/// creating a service.
135///
136/// # Example
137///
138/// ```
139/// use ntex_service::{ServiceFactory, fn_factory, fn_service};
140///
141/// # async fn example() -> Result<(), ()> {
142/// let factory = fn_factory(async |_: &()| {
143///     Ok::<_, ()>(fn_service(async |_: u32| Err::<u32, _>("unavailable")))
144/// })
145/// .map_err(String::from);
146///
147/// let pipeline = factory.pipeline(()).await?;
148/// assert_eq!(pipeline.call(1).await, Err(String::from("unavailable")));
149/// # Ok(())
150/// # }
151/// ```
152pub struct MapErrFactory<F, Sf, E> {
153    f: F,
154    sf: Sf,
155    e: PhantomData<fn(Sf) -> E>,
156}
157
158impl<F, Sf, E> MapErrFactory<F, Sf, E> {
159    /// Creates a new `MapErrFactory`.
160    pub(crate) fn new<St, Req>(f: F, sf: Sf) -> Self
161    where
162        Sf: ServiceFactory<St, Req>,
163        F: Fn(Sf::Error) -> E + Clone,
164    {
165        Self {
166            f,
167            sf,
168            e: PhantomData,
169        }
170    }
171}
172
173impl<F: Clone, Sf: Clone, E> Clone for MapErrFactory<F, Sf, E> {
174    fn clone(&self) -> Self {
175        Self {
176            f: self.f.clone(),
177            sf: self.sf.clone(),
178            e: PhantomData,
179        }
180    }
181}
182
183impl<F, Sf, E> fmt::Debug for MapErrFactory<F, Sf, E>
184where
185    Sf: fmt::Debug,
186{
187    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
188        f.debug_struct("MapErrFactory")
189            .field("sf", &self.sf)
190            .field("map", &std::any::type_name::<F>())
191            .finish()
192    }
193}
194
195impl<F, Sf, St, Req, E> ServiceFactory<St, Req> for MapErrFactory<F, Sf, E>
196where
197    Sf: ServiceFactory<St, Req>,
198    F: Fn(Sf::Error) -> E + Clone,
199{
200    type Res = Sf::Res;
201    type Error = E;
202
203    type Service = MapErr<F, Sf::Service, E>;
204    type InitError = Sf::InitError;
205
206    #[inline]
207    async fn create(&self, st: &St) -> Result<Self::Service, Self::InitError> {
208        self.sf.create(st).await.map(|svc| MapErr {
209            svc,
210            f: self.f.clone(),
211            e: PhantomData,
212        })
213    }
214}
215
216#[cfg(test)]
217#[path = "../tests/unit/map_err.rs"]
218mod tests;