about summary refs log tree commit diff
path: root/src/json_errors.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/json_errors.rs')
-rw-r--r--src/json_errors.rs118
1 files changed, 118 insertions, 0 deletions
diff --git a/src/json_errors.rs b/src/json_errors.rs
new file mode 100644
index 0000000..458eea9
--- /dev/null
+++ b/src/json_errors.rs
@@ -0,0 +1,118 @@
+//! Make every client error answer in the API's own envelope.
+//!
+//! Extractor failures never reach a handler, so they never see `ApiError`: axum
+//! answers a body it cannot deserialize with `text/plain`, e.g.
+//!
+//! ```text
+//! Failed to deserialize the JSON body into the target type:
+//! missing field `trait_name` at line 1 column 1387
+//! ```
+//!
+//! That is the one error class a client cannot parse -- everything else carries
+//! `code`, `detail` and `request_id`.  Measured on the release service: a
+//! `/compute/rqtl` call without `trait_name` answered 422 `text/plain`.
+//!
+//! A middleware fixes it in one place instead of adding a custom extractor to
+//! every handler: if the response is a 4xx that is not already JSON, its body
+//! becomes `{"type": "/errors/invalid_request", "title": ..., "status": ...,
+//! "code": "invalid_request", "detail": <the original text>, "error": null,
+//! "operation_id": <the matched route>}`.
+use axum::body::Body;
+use axum::extract::MatchedPath;
+use axum::http::{header, Request, StatusCode};
+use axum::middleware::Next;
+use axum::response::Response;
+
+pub async fn jsonify_client_errors(request: Request<Body>, next: Next) -> Response {
+    // The matched route pattern is the closest thing to an operation id
+    // available this early; it names /compute/rqtl rather than the path asked.
+    let operation = request
+        .extensions()
+        .get::<MatchedPath>()
+        .map(|matched: &MatchedPath| matched.as_str().to_string());
+    let mut response = next.run(request).await;
+    let status = response.status();
+    if !status.is_client_error() {
+        return response;
+    }
+    let is_json = response
+        .headers()
+        .get(header::CONTENT_TYPE)
+        .and_then(|value| value.to_str().ok())
+        .map(|value| value.starts_with("application/json"))
+        .unwrap_or(false);
+    if is_json {
+        return response;
+    }
+    // Take the body apart and rebuild it: the original text is the detail.
+    let (mut parts, body) = response.into_parts();
+    let bytes = axum::body::to_bytes(body, 64 * 1024)
+        .await
+        .unwrap_or_default();
+    let detail = String::from_utf8_lossy(&bytes).trim().to_string();
+    let body = serde_json::json!({
+        "type": "/errors/invalid_request",
+        "title": "Invalid request",
+        "status": status.as_u16(),
+        "code": match status {
+            StatusCode::UNSUPPORTED_MEDIA_TYPE => "unsupported_media_type",
+            StatusCode::PAYLOAD_TOO_LARGE => "payload_too_large",
+            _ => "invalid_request",
+        },
+        "detail": if detail.is_empty() { "the request could not be read".to_string() } else { detail },
+        "error": null,
+        "operation_id": operation,
+        "spec_url": "/openapi.json",
+        "next": null,
+    });
+    let text = body.to_string();
+    parts.headers.insert(
+        header::CONTENT_TYPE,
+        header::HeaderValue::from_static("application/json"),
+    );
+    parts.headers.remove(header::CONTENT_LENGTH);
+    Response::from_parts(parts, Body::from(text))
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use axum::Router;
+    use axum::routing::post;
+
+    async fn boom() -> StatusCode {
+        StatusCode::BAD_REQUEST
+    }
+
+    /// A 4xx that is not JSON comes back as the envelope; a JSON one is left
+    /// alone.
+    #[tokio::test]
+    async fn a_plain_text_client_error_becomes_the_envelope() {
+        use tower::ServiceExt;
+        let app = Router::new()
+            .route("/boom", post(boom))
+            .layer(axum::middleware::from_fn(jsonify_client_errors));
+        let response = app
+            .oneshot(
+                Request::builder()
+                    .method("POST")
+                    .uri("/boom")
+                    .body(Body::empty())
+                    .unwrap(),
+            )
+            .await
+            .unwrap();
+        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
+        assert_eq!(
+            response
+                .headers()
+                .get(header::CONTENT_TYPE)
+                .and_then(|v| v.to_str().ok()),
+            Some("application/json")
+        );
+        let bytes = axum::body::to_bytes(response.into_body(), 4096).await.unwrap();
+        let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
+        assert_eq!(body["code"], "invalid_request");
+        assert!(body["operation_id"].is_string());
+    }
+}