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
8pub 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 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::ExtractionError(_) => StatusCode::UNPROCESSABLE_ENTITY,
47 CrwError::RateLimited => StatusCode::TOO_MANY_REQUESTS,
48 _ => StatusCode::INTERNAL_SERVER_ERROR,
49 };
50
51 let error_code = self.0.error_code().to_string();
52 let body = ApiResponse::<()>::err_with_code(self.0.to_string(), error_code);
53 (status, Json(body)).into_response()
54 }
55}
56
57#[cfg(test)]
58mod tests {
59 use super::*;
60 use axum::http::StatusCode;
61
62 fn status_for(err: CrwError) -> StatusCode {
63 let app_err = AppError(err);
64 let response = app_err.into_response();
65 response.status()
66 }
67
68 #[test]
69 fn app_error_invalid_request_400() {
70 assert_eq!(
71 status_for(CrwError::InvalidRequest("bad".into())),
72 StatusCode::BAD_REQUEST
73 );
74 }
75
76 #[test]
77 fn app_error_not_found_404() {
78 assert_eq!(
79 status_for(CrwError::NotFound("missing".into())),
80 StatusCode::NOT_FOUND
81 );
82 }
83
84 #[test]
85 fn app_error_timeout_504() {
86 assert_eq!(
87 status_for(CrwError::Timeout(5000)),
88 StatusCode::GATEWAY_TIMEOUT
89 );
90 }
91
92 #[test]
93 fn app_error_http_error_502() {
94 assert_eq!(
95 status_for(CrwError::HttpError("fail".into())),
96 StatusCode::BAD_GATEWAY
97 );
98 }
99
100 #[test]
101 fn app_error_extraction_422() {
102 assert_eq!(
103 status_for(CrwError::ExtractionError("parse fail".into())),
104 StatusCode::UNPROCESSABLE_ENTITY
105 );
106 }
107
108 #[test]
109 fn app_error_internal_500() {
110 assert_eq!(
111 status_for(CrwError::Internal("oops".into())),
112 StatusCode::INTERNAL_SERVER_ERROR
113 );
114 }
115
116 #[test]
117 fn app_error_renderer_500() {
118 assert_eq!(
119 status_for(CrwError::RendererError("cdp fail".into())),
120 StatusCode::INTERNAL_SERVER_ERROR
121 );
122 }
123
124 #[tokio::test]
125 async fn app_error_body_is_api_response() {
126 let app_err = AppError(CrwError::InvalidRequest("test error".into()));
127 let response = app_err.into_response();
128 assert_eq!(response.status(), StatusCode::BAD_REQUEST);
129
130 let body = axum::body::to_bytes(response.into_body(), 1024 * 1024)
131 .await
132 .unwrap();
133 let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
134 assert_eq!(json["success"], false);
135 assert!(json["error"].as_str().unwrap().contains("test error"));
136 }
137}