diff options
| author | Pjotr Prins <pjotr.public01@thebird.nl> | 2026-11-22 17:04:30 +0000 |
|---|---|---|
| committer | Pjotr Prins <pjotr.public01@thebird.nl> | 2026-11-22 17:04:30 +0000 |
| commit | 3854e38fd8c4521df1f501dd6b093fe8b27a840a (patch) | |
| tree | 205b7f9212d0be2149fa2ef55af366822f9e7de0 /src/json_errors.rs | |
| parent | 52e4f6d9b92242d241be85a91699d8565e4a746a (diff) | |
| download | genenetwork4-3854e38fd8c4521df1f501dd6b093fe8b27a840a.tar.gz | |
api: a request body it cannot read answers in the envelope, not in text/plain
An extractor's rejection never reaches a handler, so it never sees ApiError: axum answered "Failed to deserialize the JSON body ...: missing field `trait_name`" as text/plain. That is the one error class a client cannot parse, and it is the class a client most likely triggers. A middleware outside everything turns any non-JSON 4xx into the usual envelope, with the matched route as the operation id and the original text as the detail.
Diffstat (limited to 'src/json_errors.rs')
| -rw-r--r-- | src/json_errors.rs | 118 |
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()); + } +} |
