1use actix_web::{
2 body::MessageBody,
3 dev::{Service, ServiceRequest, ServiceResponse, Transform},
4 Error,
5};
6use futures::{
7 future::{ok, LocalBoxFuture, Ready},
8 FutureExt,
9};
10use std::{
11 panic::AssertUnwindSafe,
12 task::{Context, Poll},
13};
14
15#[derive(Clone)]
17pub struct Recover {
18 response_body: String,
19}
20
21impl Default for Recover {
22 fn default() -> Self {
23 Self {
24 response_body: "internal server error".to_owned(),
25 }
26 }
27}
28
29impl Recover {
30 pub fn new() -> Self {
31 Self::default()
32 }
33
34 pub fn with_response_body(mut self, body: impl Into<String>) -> Self {
35 self.response_body = body.into();
36 self
37 }
38}
39
40impl<S, B> Transform<S, ServiceRequest> for Recover
41where
42 S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static,
43 S::Future: 'static,
44 B: MessageBody + 'static,
45{
46 type Response = ServiceResponse<B>;
47 type Error = Error;
48 type Transform = RecoverMiddleware<S>;
49 type InitError = ();
50 type Future = Ready<Result<Self::Transform, Self::InitError>>;
51
52 fn new_transform(&self, service: S) -> Self::Future {
53 ok(RecoverMiddleware {
54 service,
55 response_body: self.response_body.clone(),
56 })
57 }
58}
59
60pub struct RecoverMiddleware<S> {
61 service: S,
62 response_body: String,
63}
64
65impl<S, B> Service<ServiceRequest> for RecoverMiddleware<S>
66where
67 S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static,
68 S::Future: 'static,
69 B: MessageBody + 'static,
70{
71 type Response = ServiceResponse<B>;
72 type Error = Error;
73 type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;
74
75 fn poll_ready(&self, context: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
76 self.service.poll_ready(context)
77 }
78
79 fn call(&self, request: ServiceRequest) -> Self::Future {
80 let response_body = self.response_body.clone();
81 let future = self.service.call(request);
82
83 Box::pin(async move {
84 match AssertUnwindSafe(future).catch_unwind().await {
85 Ok(response) => response,
86 Err(_) => {
87 tracing::error!("recovered panic while handling HTTP request");
88 Err(actix_web::error::ErrorInternalServerError(response_body))
89 }
90 }
91 })
92 }
93}
94
95#[cfg(test)]
96mod tests {
97 use super::*;
98 use actix_web::{http::StatusCode, test, web, App};
99
100 #[actix_rt::test]
101 async fn converts_handler_panics_to_internal_server_errors() {
102 let app = test::init_service(App::new().wrap(Recover::new()).route(
103 "/",
104 web::get().to(|| async {
105 panic!("boom");
106 #[allow(unreachable_code)]
107 "never"
108 }),
109 ))
110 .await;
111
112 let error = test::try_call_service(&app, test::TestRequest::get().uri("/").to_request())
113 .await
114 .unwrap_err();
115
116 assert_eq!(
117 actix_web::error::ResponseError::status_code(error.as_response_error()),
118 StatusCode::INTERNAL_SERVER_ERROR
119 );
120 }
121}