loveyu-kit 0.2.0

面向 Axum 项目的可组合 API 工具库
Documentation
use std::any::Any;

use axum::{
    http::StatusCode,
    response::{IntoResponse, Response},
};

use crate::web::response::ApiError;

/// panic 恢复配置。
///
/// panic 的真实内容只会进入服务端错误日志,客户端仅能看到这里配置的业务码和提示信息。
#[derive(Clone, Debug)]
#[must_use = "配置需要传给 RequestLoggingConfig 才会生效"]
pub struct PanicRecoveryConfig {
    pub(crate) code: u32,
    pub(crate) client_message: String,
    pub(crate) http_status: StatusCode,
}

impl Default for PanicRecoveryConfig {
    fn default() -> Self {
        Self {
            code: 500_000,
            client_message: "系统内部错误".into(),
            http_status: StatusCode::INTERNAL_SERVER_ERROR,
        }
    }
}

impl PanicRecoveryConfig {
    /// 创建默认配置。
    pub fn new() -> Self {
        Self::default()
    }

    /// 设置返回给客户端的业务错误码。
    pub const fn with_code(mut self, code: u32) -> Self {
        self.code = code;
        self
    }

    /// 设置返回给客户端的安全提示信息。
    pub fn with_client_message(mut self, message: impl Into<String>) -> Self {
        self.client_message = message.into();
        self
    }

    /// 设置 panic 响应的 HTTP 状态码。
    pub const fn with_http_status(mut self, status: StatusCode) -> Self {
        self.http_status = status;
        self
    }
}

#[allow(clippy::needless_pass_by_value)]
pub(super) fn response_for_panic(
    payload: Box<dyn Any + Send + 'static>,
    config: &PanicRecoveryConfig,
) -> Response {
    let panic_message = panic_payload_message(payload.as_ref());

    ApiError::new(config.code, config.client_message.clone())
        .with_error(panic_message)
        .with_http_status(config.http_status)
        .with_context("error_type", "panic")
        .into_response()
}

fn panic_payload_message<'payload>(payload: &'payload (dyn Any + Send + 'static)) -> &'payload str {
    payload.downcast_ref::<String>().map_or_else(
        || {
            payload
                .downcast_ref::<&str>()
                .map_or_else(|| "发生 panic,但其内容不是字符串", |message| *message)
        },
        String::as_str,
    )
}

#[cfg(test)]
mod tests {
    use http_body_util::BodyExt;

    use super::*;

    #[test]
    fn reads_string_panic_payload() {
        let payload: Box<dyn Any + Send> = Box::new("测试 panic".to_owned());
        assert_eq!(panic_payload_message(payload.as_ref()), "测试 panic");
    }

    #[test]
    fn handles_non_string_panic_payload() {
        let payload: Box<dyn Any + Send> = Box::new(100_u32);
        assert_eq!(
            panic_payload_message(payload.as_ref()),
            "发生 panic,但其内容不是字符串"
        );
    }

    #[tokio::test]
    async fn custom_recovery_config_controls_safe_client_response() {
        let config = PanicRecoveryConfig::new()
            .with_code(500_099)
            .with_client_message("服务暂时不可用")
            .with_http_status(StatusCode::SERVICE_UNAVAILABLE);
        let response = response_for_panic(Box::new("内部 panic"), &config);

        assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
        let body = response.into_body().collect().await.unwrap().to_bytes();
        let value: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(value["code"], 500_099);
        assert_eq!(value["msg"], "服务暂时不可用");
        assert!(!String::from_utf8_lossy(&body).contains("内部 panic"));
    }
}