1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
//! panic catcher middleware.

use xitca_http::util::middleware::catch_unwind::{self, CatchUnwindError};

use crate::{
    error::{Error, ThreadJoinError},
    service::{ready::ReadyService, Service},
    WebContext,
};

/// middleware for catching panic inside [`Service::call`] and return a 500 error response.
///
/// # Examples:
/// ```rust
/// # use xitca_web::{handler::handler_service, middleware::CatchUnwind, service::ServiceExt, App, WebContext};
/// // handler function that cause panic.
/// async fn handler(_: &WebContext<'_>) -> &'static str {
///     panic!("");
/// }
///
/// App::new()
///     // request to "/" would always panic due to handler function.
///     .at("/", handler_service(handler))
///     // enclosed application with CatchUnwind middleware.
///     // panic in handler function would be caught and converted to 500 internal server error response to client.
///     .enclosed(CatchUnwind);
///
/// // CatchUnwind can also be used on individual route service for scoped panic catching:
/// App::new()
///     .at("/", handler_service(handler))
///     // only catch panic on "/scope" path.
///     .at("/scope", handler_service(handler).enclosed(CatchUnwind));
/// ```
pub struct CatchUnwind;

impl<Arg> Service<Arg> for CatchUnwind
where
    catch_unwind::CatchUnwind: Service<Arg>,
{
    type Response = CatchUnwindService<<catch_unwind::CatchUnwind as Service<Arg>>::Response>;
    type Error = <catch_unwind::CatchUnwind as Service<Arg>>::Error;

    async fn call(&self, arg: Arg) -> Result<Self::Response, Self::Error> {
        catch_unwind::CatchUnwind.call(arg).await.map(CatchUnwindService)
    }
}

pub struct CatchUnwindService<S>(S);

impl<'r, C, B, S> Service<WebContext<'r, C, B>> for CatchUnwindService<S>
where
    S: Service<WebContext<'r, C, B>>,
    S::Error: Into<Error<C>>,
{
    type Response = S::Response;
    type Error = Error<C>;

    #[inline]
    async fn call(&self, ctx: WebContext<'r, C, B>) -> Result<Self::Response, Self::Error> {
        self.0.call(ctx).await.map_err(Into::into)
    }
}

impl<C, E> From<CatchUnwindError<E>> for Error<C>
where
    E: Into<Error<C>>,
{
    fn from(e: CatchUnwindError<E>) -> Self {
        match e {
            CatchUnwindError::First(e) => Error::from(ThreadJoinError::new(e)),
            CatchUnwindError::Second(e) => e.into(),
        }
    }
}

impl<S> ReadyService for CatchUnwindService<S>
where
    S: ReadyService,
{
    type Ready = S::Ready;

    #[inline]
    async fn ready(&self) -> Self::Ready {
        self.0.ready().await
    }
}

#[cfg(test)]
mod test {
    use xitca_unsafe_collection::futures::NowOrPanic;

    use crate::{
        handler::handler_service,
        http::{Request, StatusCode},
        App,
    };

    use super::*;

    #[test]
    fn catch_panic() {
        async fn handler() -> &'static str {
            panic!("");
        }

        let res = App::new()
            .with_state("996")
            .at("/", handler_service(handler))
            .enclosed(CatchUnwind)
            .finish()
            .call(())
            .now_or_panic()
            .unwrap()
            .call(Request::default())
            .now_or_panic()
            .unwrap();

        assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);
    }
}