Skip to main content

crw_server/
error.rs

1use axum::Json;
2use axum::extract::rejection::JsonRejection;
3use axum::http::StatusCode;
4use axum::response::{IntoResponse, Response};
5use crw_core::error::CrwError;
6use crw_core::types::ApiResponse;
7
8/// Wrapper to implement IntoResponse for CrwError in the server crate.
9pub struct AppError(pub CrwError);
10
11impl From<CrwError> for AppError {
12    fn from(e: CrwError) -> Self {
13        Self(e)
14    }
15}
16
17impl From<JsonRejection> for AppError {
18    fn from(rejection: JsonRejection) -> Self {
19        let msg = match &rejection {
20            JsonRejection::JsonDataError(_) => {
21                let raw = rejection.body_text();
22                // Strip internal Rust type paths, keep the user-readable part.
23                if let Some(pos) = raw.find(": ") {
24                    format!("Invalid request body: {}", &raw[pos + 2..])
25                } else {
26                    format!("Invalid request body: {raw}")
27                }
28            }
29            JsonRejection::JsonSyntaxError(_) => "Invalid JSON syntax in request body".to_string(),
30            JsonRejection::MissingJsonContentType(_) => {
31                "Missing Content-Type: application/json header".to_string()
32            }
33            _ => "Invalid request body".to_string(),
34        };
35        Self(CrwError::InvalidRequest(msg))
36    }
37}
38
39impl IntoResponse for AppError {
40    fn into_response(self) -> Response {
41        let status = match &self.0 {
42            CrwError::InvalidRequest(_) => StatusCode::BAD_REQUEST,
43            CrwError::NotFound(_) => StatusCode::NOT_FOUND,
44            CrwError::Timeout(_) => StatusCode::GATEWAY_TIMEOUT,
45            CrwError::HttpError(_) => StatusCode::BAD_GATEWAY,
46            CrwError::TargetUnreachable(_) => StatusCode::UNPROCESSABLE_ENTITY,
47            CrwError::ExtractionError(_) => StatusCode::UNPROCESSABLE_ENTITY,
48            CrwError::RateLimited => StatusCode::TOO_MANY_REQUESTS,
49            _ => StatusCode::INTERNAL_SERVER_ERROR,
50        };
51
52        let error_code = self.0.error_code().to_string();
53        let body = ApiResponse::<()>::err_with_code(self.0.to_string(), error_code);
54        (status, Json(body)).into_response()
55    }
56}
57
58#[cfg(test)]
59mod tests {
60    use super::*;
61    use axum::http::StatusCode;
62
63    fn status_for(err: CrwError) -> StatusCode {
64        let app_err = AppError(err);
65        let response = app_err.into_response();
66        response.status()
67    }
68
69    #[test]
70    fn app_error_invalid_request_400() {
71        assert_eq!(
72            status_for(CrwError::InvalidRequest("bad".into())),
73            StatusCode::BAD_REQUEST
74        );
75    }
76
77    #[test]
78    fn app_error_not_found_404() {
79        assert_eq!(
80            status_for(CrwError::NotFound("missing".into())),
81            StatusCode::NOT_FOUND
82        );
83    }
84
85    #[test]
86    fn app_error_timeout_504() {
87        assert_eq!(
88            status_for(CrwError::Timeout(5000)),
89            StatusCode::GATEWAY_TIMEOUT
90        );
91    }
92
93    #[test]
94    fn app_error_http_error_502() {
95        assert_eq!(
96            status_for(CrwError::HttpError("fail".into())),
97            StatusCode::BAD_GATEWAY
98        );
99    }
100
101    #[test]
102    fn app_error_extraction_422() {
103        assert_eq!(
104            status_for(CrwError::ExtractionError("parse fail".into())),
105            StatusCode::UNPROCESSABLE_ENTITY
106        );
107    }
108
109    #[test]
110    fn app_error_internal_500() {
111        assert_eq!(
112            status_for(CrwError::Internal("oops".into())),
113            StatusCode::INTERNAL_SERVER_ERROR
114        );
115    }
116
117    #[test]
118    fn app_error_renderer_500() {
119        assert_eq!(
120            status_for(CrwError::RendererError("cdp fail".into())),
121            StatusCode::INTERNAL_SERVER_ERROR
122        );
123    }
124
125    #[tokio::test]
126    async fn app_error_body_is_api_response() {
127        let app_err = AppError(CrwError::InvalidRequest("test error".into()));
128        let response = app_err.into_response();
129        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
130
131        let body = axum::body::to_bytes(response.into_body(), 1024 * 1024)
132            .await
133            .unwrap();
134        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
135        assert_eq!(json["success"], false);
136        assert!(json["error"].as_str().unwrap().contains("test error"));
137    }
138}