Skip to main content

adk_awp/
error_response.rs

1//! AWP error to HTTP response conversion.
2//!
3//! Uses a function approach instead of `IntoResponse` impl to avoid Rust's
4//! orphan rule (both `IntoResponse` and `AwpError` are foreign types).
5
6use awp_types::{AwpError, CURRENT_VERSION};
7use axum::Json;
8use axum::http::StatusCode;
9use axum::response::{IntoResponse, Response};
10
11/// Convert an [`AwpError`] into an Axum HTTP [`Response`].
12///
13/// The response includes:
14/// - HTTP status code from [`AwpError::status_code()`]
15/// - JSON body with `error`, `message`, and `version` fields
16/// - `Retry-After` header for [`AwpError::RateLimited`] errors
17///
18/// # Example
19///
20/// ```
21/// use awp_types::AwpError;
22/// use adk_awp::error_response::awp_error_response;
23///
24/// let err = AwpError::NotFound("resource xyz".to_string());
25/// let response = awp_error_response(err);
26/// assert_eq!(response.status(), 404);
27/// ```
28pub fn awp_error_response(err: AwpError) -> Response {
29    let status =
30        StatusCode::from_u16(err.status_code()).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
31    let body = serde_json::json!({
32        "error": err.error_code(),
33        "message": err.to_string(),
34        "version": CURRENT_VERSION.to_string(),
35    });
36
37    let mut response = (status, Json(body)).into_response();
38
39    if let AwpError::RateLimited { retry_after_secs } = &err
40        && let Ok(val) = retry_after_secs.to_string().parse()
41    {
42        response.headers_mut().insert("Retry-After", val);
43    }
44
45    response
46}
47
48/// Newtype wrapper for [`AwpError`] that implements [`IntoResponse`].
49///
50/// Use this when you need to return an `AwpError` directly from an Axum handler.
51pub struct AwpErrorResponse(pub AwpError);
52
53impl IntoResponse for AwpErrorResponse {
54    fn into_response(self) -> Response {
55        awp_error_response(self.0)
56    }
57}
58
59#[cfg(test)]
60mod tests {
61    use super::*;
62    use awp_types::AwpVersion;
63    use axum::body::to_bytes;
64
65    #[tokio::test]
66    async fn test_not_found_response() {
67        let err = AwpError::NotFound("resource xyz".to_string());
68        let response = awp_error_response(err);
69        assert_eq!(response.status(), StatusCode::NOT_FOUND);
70
71        let body = to_bytes(response.into_body(), 1024).await.unwrap();
72        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
73        assert_eq!(json["error"], "not_found");
74        assert_eq!(json["version"], "1.0");
75    }
76
77    #[tokio::test]
78    async fn test_rate_limited_response_has_retry_after() {
79        let err = AwpError::RateLimited { retry_after_secs: 30 };
80        let response = awp_error_response(err);
81        assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);
82        assert_eq!(response.headers().get("Retry-After").unwrap(), "30");
83    }
84
85    #[tokio::test]
86    async fn test_version_mismatch_response() {
87        let err = AwpError::VersionMismatch {
88            requested: AwpVersion { major: 2, minor: 0 },
89            current: CURRENT_VERSION,
90        };
91        let response = awp_error_response(err);
92        assert_eq!(response.status(), StatusCode::NOT_ACCEPTABLE);
93    }
94
95    #[tokio::test]
96    async fn test_error_response_wrapper() {
97        let err = AwpErrorResponse(AwpError::Unauthorized("no token".to_string()));
98        let response = err.into_response();
99        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
100    }
101
102    #[tokio::test]
103    async fn test_internal_error_response() {
104        let err = AwpError::InternalError("something broke".to_string());
105        let response = awp_error_response(err);
106        assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
107
108        let body = to_bytes(response.into_body(), 1024).await.unwrap();
109        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
110        assert_eq!(json["error"], "internal_error");
111        assert!(json["message"].as_str().unwrap().contains("something broke"));
112    }
113}