Skip to content

Commit 6e0de1b

Browse files
Simplify error handler middleware
1 parent a227653 commit 6e0de1b

File tree

1 file changed

+15
-18
lines changed

1 file changed

+15
-18
lines changed

src/main.rs

+15-18
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,13 @@ use axum::{
1616
extract::{Path, Query, Request, State},
1717
handler::Handler,
1818
http::{
19-
header::{ACCEPT, CACHE_CONTROL, CONTENT_LENGTH, CONTENT_TYPE},
19+
header::{ACCEPT, CACHE_CONTROL, CONTENT_TYPE},
2020
HeaderName, HeaderValue, StatusCode,
2121
},
2222
middleware::Next,
2323
response::{IntoResponse, Redirect, Response},
2424
routing::get,
25-
Extension, RequestExt, Router,
25+
Extension, Router,
2626
};
2727
use axum_extra::routing::RouterExt;
2828
use base64::{prelude::BASE64_STANDARD, Engine};
@@ -451,22 +451,24 @@ impl<T: Serialize> IntoResponse for Json<T> {
451451
}
452452
}
453453

454-
async fn error_middleware(State(state): State<AppState>, mut req: Request, next: Next) -> Response {
454+
async fn error_middleware(
455+
State(state): State<AppState>,
456+
CspNonce(nonce): CspNonce,
457+
req: Request,
458+
next: Next,
459+
) -> Response {
455460
let json = req
456461
.headers()
457462
.get(ACCEPT)
458463
.is_some_and(|v| v.to_str().is_ok_and(|v| v.contains("application/json")));
459-
let nonce = match req.extract_parts::<CspNonce>().await {
460-
Ok(CspNonce(n)) => n,
461-
Err(err) => return err.into_response(),
462-
};
463464
let mut resp = next.run(req).await;
464465
if let Some(failure) = resp.extensions().get::<Arc<Failure>>().cloned() {
465466
let error = failure.to_string();
466-
let body = if json {
467+
let status = resp.status();
468+
if json {
467469
resp.headers_mut().insert(CONTENT_TYPE, JSON_CTYPE.clone());
468470
let error = ErrorSerialization { error };
469-
infallible_json_serialize(&error)
471+
(status, Json(infallible_json_serialize(&error))).into_response()
470472
} else {
471473
resp.headers_mut().insert(CONTENT_TYPE, HTML_CTYPE.clone());
472474
let error = ErrorTemplate {
@@ -475,16 +477,11 @@ async fn error_middleware(State(state): State<AppState>, mut req: Request, next:
475477
root_url: state.root_url,
476478
nonce,
477479
};
478-
error
479-
.render()
480-
.unwrap_or_else(|e| format!("error rendering template: {e}"))
481-
.into_bytes()
482-
};
483-
resp.headers_mut()
484-
.insert(CONTENT_LENGTH, HeaderValue::from(body.len()));
485-
*resp.body_mut() = Body::from(body);
480+
(status, error).into_response()
481+
}
482+
} else {
483+
resp
486484
}
487-
resp
488485
}
489486

490487
pub struct Png(pub Vec<u8>);

0 commit comments

Comments
 (0)