swadhinbiswas refactor(core): unify error responses on {"detail": ...}; 404 no longer aborts without fallback · 7/15/2026
cf9adbf
68 lines · 2.3 KB
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
use std::sync::Arc;

use futures::FutureExt;
use hyper::body::Incoming;
use hyper::{Request, StatusCode};

use crate::json_response;
use crate::middleware::HandlerFn;

/// Wraps a handler fn so that panics are caught, logged, and converted to 500 responses.
pub fn with_panic_recovery(handler: HandlerFn) -> HandlerFn {
    Arc::new(move |req: Request<Incoming>| {
        let handler = handler.clone();
        Box::pin(async move {
            let prev = std::panic::take_hook();
            std::panic::set_hook(Box::new(|info| {
                let msg = info
                    .payload()
                    .downcast_ref::<&str>()
                    .map(|s| s.to_string())
                    .or_else(|| info.payload().downcast_ref::<String>().cloned())
                    .unwrap_or_else(|| "unknown panic".to_string());
                let location = info.location().map(|l| l.to_string()).unwrap_or_default();
                tracing::error!(
                    panic = true,
                    message = %msg,
                    location = %location,
                    "Handler panicked"
                );
            }));

            let result = std::panic::AssertUnwindSafe(handler(req)).catch_unwind().await;

            std::panic::set_hook(prev);

            match result {
                Ok(Ok(resp)) => Ok(resp),
                Ok(Err(e)) => {
                    tracing::error!(error = %e, "Handler returned error");
                    Ok(json_response(
                        StatusCode::INTERNAL_SERVER_ERROR,
                        r#"{"detail":"Internal error"}"#,
                    ))
                }
                Err(_panic) => Ok(json_response(
                    StatusCode::INTERNAL_SERVER_ERROR,
                    r#"{"detail":"Internal server error"}"#,
                )),
            }
        })
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_with_panic_recovery_returns_handler_fn() {
        let handler: HandlerFn = Arc::new(|_req: Request<Incoming>| {
            Box::pin(async { Ok(json_response(StatusCode::OK, "ok")) })
        });
        let wrapped = with_panic_recovery(handler);
        // Smoke test: the wrapper is itself a HandlerFn with the same signature.
        let _wrapped_ref: &HandlerFn = &wrapped;
    }
}