tower_async/util/
map_err.rs1use std::fmt;
2
3use tower_async_layer::Layer;
4use tower_async_service::Service;
5
6#[derive(Clone)]
10pub struct MapErr<S, F> {
11 inner: S,
12 f: F,
13}
14
15impl<S, F> fmt::Debug for MapErr<S, F>
16where
17 S: fmt::Debug,
18{
19 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
20 f.debug_struct("MapErr")
21 .field("inner", &self.inner)
22 .field("f", &format_args!("{}", std::any::type_name::<F>()))
23 .finish()
24 }
25}
26
27#[derive(Clone, Debug)]
31pub struct MapErrLayer<F> {
32 f: F,
33}
34
35impl<S, F> MapErr<S, F> {
36 pub fn new(inner: S, f: F) -> Self {
38 MapErr { f, inner }
39 }
40
41 pub fn layer(f: F) -> MapErrLayer<F> {
47 MapErrLayer { f }
48 }
49}
50
51impl<S, F, Request, Error> Service<Request> for MapErr<S, F>
52where
53 S: Service<Request>,
54 F: Fn(S::Error) -> Error,
55{
56 type Response = S::Response;
57 type Error = Error;
58
59 #[inline]
60 async fn call(&self, request: Request) -> Result<Self::Response, Self::Error> {
61 match self.inner.call(request).await {
62 Ok(response) => Ok(response),
63 Err(error) => Err((self.f)(error)),
64 }
65 }
66}
67
68impl<F> MapErrLayer<F> {
69 pub fn new(f: F) -> Self {
71 MapErrLayer { f }
72 }
73}
74
75impl<S, F> Layer<S> for MapErrLayer<F>
76where
77 F: Clone,
78{
79 type Service = MapErr<S, F>;
80
81 fn layer(&self, inner: S) -> Self::Service {
82 MapErr {
83 f: self.f.clone(),
84 inner,
85 }
86 }
87}