1pub use axum_problem_derive::AxumProblem;
57
58use axum::response::{IntoResponse, Response};
59use http::{header, StatusCode};
60use serde::Serialize;
61
62#[derive(Debug, Clone, Serialize)]
93pub struct Problem {
94 #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
96 pub problem_type: Option<String>,
97
98 pub title: String,
100
101 pub status: u16,
103
104 #[serde(skip_serializing_if = "Option::is_none")]
106 pub detail: Option<String>,
107
108 #[serde(skip_serializing_if = "Option::is_none")]
110 pub instance: Option<String>,
111
112 #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
116 pub extensions: serde_json::Map<String, serde_json::Value>,
117}
118
119impl Problem {
120 pub fn new(status: u16) -> Self {
123 Self {
124 problem_type: None,
125 title: status_title(status).to_owned(),
126 status,
127 detail: None,
128 instance: None,
129 extensions: serde_json::Map::new(),
130 }
131 }
132
133 pub fn extension(mut self, key: impl Into<String>, value: impl Into<serde_json::Value>) -> Self {
144 self.extensions.insert(key.into(), value.into());
145 self
146 }
147
148 pub fn problem_type(mut self, t: impl Into<String>) -> Self {
150 self.problem_type = Some(t.into());
151 self
152 }
153
154 pub fn title(mut self, title: impl Into<String>) -> Self {
156 self.title = title.into();
157 self
158 }
159
160 pub fn detail(mut self, detail: impl Into<String>) -> Self {
162 self.detail = Some(detail.into());
163 self
164 }
165
166 pub fn instance(mut self, instance: impl Into<String>) -> Self {
168 self.instance = Some(instance.into());
169 self
170 }
171
172 pub fn bad_request() -> Self { Self::new(400) }
175 pub fn unauthorized() -> Self { Self::new(401) }
176 pub fn forbidden() -> Self { Self::new(403) }
177 pub fn not_found() -> Self { Self::new(404) }
178 pub fn method_not_allowed() -> Self { Self::new(405) }
179 pub fn conflict() -> Self { Self::new(409) }
180 pub fn unprocessable_entity() -> Self { Self::new(422) }
181 pub fn too_many_requests() -> Self { Self::new(429) }
182 pub fn internal_server_error() -> Self { Self::new(500) }
183 pub fn not_implemented() -> Self { Self::new(501) }
184 pub fn service_unavailable() -> Self { Self::new(503) }
185}
186
187impl IntoResponse for Problem {
188 fn into_response(self) -> Response {
189 let status = StatusCode::from_u16(self.status)
190 .unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
191
192 let mut serializable = self;
196 serializable.status = status.as_u16();
197
198 let body = serde_json::to_string(&serializable)
199 .unwrap_or_else(|_| r#"{"title":"Internal Server Error","status":500}"#.to_owned());
200
201 (
202 status,
203 [(header::CONTENT_TYPE, "application/problem+json")],
204 body,
205 )
206 .into_response()
207 }
208}
209
210pub fn status_title(status: u16) -> &'static str {
212 match status {
213 400 => "Bad Request",
214 401 => "Unauthorized",
215 403 => "Forbidden",
216 404 => "Not Found",
217 405 => "Method Not Allowed",
218 408 => "Request Timeout",
219 409 => "Conflict",
220 410 => "Gone",
221 415 => "Unsupported Media Type",
222 422 => "Unprocessable Entity",
223 429 => "Too Many Requests",
224 500 => "Internal Server Error",
225 501 => "Not Implemented",
226 502 => "Bad Gateway",
227 503 => "Service Unavailable",
228 504 => "Gateway Timeout",
229 _ => "Error",
230 }
231}
232
233#[derive(Clone, Copy, Default)]
254pub struct ProblemLayer;
255
256impl<S> tower_layer::Layer<S> for ProblemLayer {
257 type Service = ProblemService<S>;
258 fn layer(&self, inner: S) -> Self::Service {
259 ProblemService { inner }
260 }
261}
262
263#[derive(Clone)]
265pub struct ProblemService<S> {
266 inner: S,
267}
268
269impl<S, ReqBody> tower::Service<http::Request<ReqBody>> for ProblemService<S>
270where
271 S: tower::Service<http::Request<ReqBody>, Response = axum::response::Response>
272 + Clone
273 + Send
274 + 'static,
275 S::Future: Send + 'static,
276 ReqBody: Send + 'static,
277{
278 type Response = axum::response::Response;
279 type Error = S::Error;
280 type Future = std::pin::Pin<
281 Box<dyn std::future::Future<Output = Result<Self::Response, Self::Error>> + Send>,
282 >;
283
284 fn poll_ready(
285 &mut self,
286 cx: &mut std::task::Context<'_>,
287 ) -> std::task::Poll<Result<(), Self::Error>> {
288 self.inner.poll_ready(cx)
289 }
290
291 fn call(&mut self, req: http::Request<ReqBody>) -> Self::Future {
292 use axum::response::IntoResponse;
293 let future = self.inner.call(req);
294 Box::pin(async move {
295 let resp = future.await?;
296 let status = resp.status();
297
298 if status.is_client_error() || status.is_server_error() {
299 let already_problem = resp
300 .headers()
301 .get(http::header::CONTENT_TYPE)
302 .and_then(|v| v.to_str().ok())
303 .map(|ct| ct.contains("application/problem+json"))
304 .unwrap_or(false);
305
306 if !already_problem {
307 return Ok(Problem::new(status.as_u16()).into_response());
308 }
309 }
310
311 Ok(resp)
312 })
313 }
314}
315
316#[cfg(test)]
317mod tests {
318 use super::*;
319 use axum::body::to_bytes;
320
321 async fn body_string(resp: Response) -> String {
322 let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
323 String::from_utf8(bytes.to_vec()).unwrap()
324 }
325
326 #[tokio::test]
327 async fn problem_serializes_to_correct_json() {
328 let p = Problem::not_found().detail("order 1001 not found");
329 let resp = p.into_response();
330
331 assert_eq!(resp.status(), StatusCode::NOT_FOUND);
332 assert_eq!(
333 resp.headers().get(header::CONTENT_TYPE).unwrap(),
334 "application/problem+json"
335 );
336
337 let body = body_string(resp).await;
338 let json: serde_json::Value = serde_json::from_str(&body).unwrap();
339 assert_eq!(json["status"], 404);
340 assert_eq!(json["title"], "Not Found");
341 assert_eq!(json["detail"], "order 1001 not found");
342 }
343
344 #[tokio::test]
345 async fn problem_omits_optional_fields() {
346 let p = Problem::new(400);
347 let resp = p.into_response();
348 let body = body_string(resp).await;
349 let json: serde_json::Value = serde_json::from_str(&body).unwrap();
350 assert!(json.get("detail").is_none());
351 assert!(json.get("instance").is_none());
352 assert!(json.get("type").is_none());
353 }
354
355 #[tokio::test]
356 async fn problem_with_type_uri() {
357 let p = Problem::new(422)
358 .problem_type("https://errors.example.com/validation-failed")
359 .detail("email is required");
360 let resp = p.into_response();
361 let body = body_string(resp).await;
362 let json: serde_json::Value = serde_json::from_str(&body).unwrap();
363 assert_eq!(json["type"], "https://errors.example.com/validation-failed");
364 }
365
366 #[tokio::test]
367 async fn status_title_coverage() {
368 assert_eq!(status_title(404), "Not Found");
369 assert_eq!(status_title(500), "Internal Server Error");
370 assert_eq!(status_title(999), "Error");
371 }
372
373 #[tokio::test]
376 async fn extension_field_serialized_at_top_level() {
377 let p = Problem::new(422)
378 .detail("validation failed")
379 .extension("violations", serde_json::json!([
380 {"field": "email", "message": "invalid"}
381 ]));
382
383 let resp = p.into_response();
384 let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap();
385 let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
386
387 assert!(json.get("violations").is_some(), "violations must be a top-level field");
389 assert!(json.get("extensions").is_none(), "must not have a nested 'extensions' key");
390 assert_eq!(json["violations"][0]["field"], "email");
391 assert_eq!(json["status"], 422);
392 assert_eq!(json["detail"], "validation failed");
393 }
394
395 #[tokio::test]
396 async fn multiple_extensions_all_at_top_level() {
397 let p = Problem::new(400)
398 .extension("request_id", serde_json::json!("req-abc-123"))
399 .extension("correlation_id", serde_json::json!("corr-xyz"))
400 .extension("retry_after", serde_json::json!(30));
401
402 let resp = p.into_response();
403 let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap();
404 let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
405
406 assert_eq!(json["request_id"], "req-abc-123");
407 assert_eq!(json["correlation_id"], "corr-xyz");
408 assert_eq!(json["retry_after"], 30);
409 }
410
411 #[tokio::test]
412 async fn no_extensions_means_no_extra_fields() {
413 let p = Problem::new(404).detail("not found");
414 let resp = p.into_response();
415 let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap();
416 let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
417
418 let keys: Vec<&str> = json.as_object().unwrap().keys().map(|k| k.as_str()).collect();
420 for key in &keys {
421 assert!(
422 ["title", "status", "detail", "instance", "type"].contains(key),
423 "unexpected extra key in response: {key}"
424 );
425 }
426 }
427
428 #[tokio::test]
429 async fn extension_is_valid_rfc9457_json() {
430 let p = Problem::new(400)
431 .extension("errors", serde_json::json!({"count": 3}));
432 let resp = p.into_response();
433 let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap();
434 let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
435
436 assert!(json["title"].is_string());
438 assert_eq!(json["status"], 400);
439 assert_eq!(json["errors"]["count"], 3);
441 }
442
443 use axum::{Router, routing::get, body::Body};
446 use tower::ServiceExt;
447
448 async fn handler_404() -> impl axum::response::IntoResponse {
449 (http::StatusCode::NOT_FOUND, "plain text 404")
450 }
451
452 async fn handler_200() -> impl axum::response::IntoResponse {
453 "ok"
454 }
455
456 async fn handler_problem() -> impl axum::response::IntoResponse {
457 Problem::not_found().detail("already a problem")
458 }
459
460 fn layered_app() -> Router {
461 Router::new()
462 .route("/notfound", get(handler_404))
463 .route("/ok", get(handler_200))
464 .route("/problem", get(handler_problem))
465 .layer(ProblemLayer)
466 }
467
468 async fn call(app: &Router, uri: &str) -> axum::response::Response {
469 app.clone()
470 .oneshot(
471 http::Request::builder()
472 .uri(uri)
473 .body(Body::empty())
474 .unwrap(),
475 )
476 .await
477 .unwrap()
478 }
479
480 #[tokio::test]
481 async fn problem_layer_converts_plain_404_to_problem_json() {
482 let app = layered_app();
483 let resp = call(&app, "/notfound").await;
484
485 assert_eq!(resp.status(), http::StatusCode::NOT_FOUND);
486 assert_eq!(
487 resp.headers().get(header::CONTENT_TYPE).unwrap(),
488 "application/problem+json"
489 );
490
491 let body = body_string(resp).await;
492 let json: serde_json::Value = serde_json::from_str(&body).unwrap();
493 assert_eq!(json["status"], 404);
494 assert_eq!(json["title"], "Not Found");
495 }
496
497 #[tokio::test]
498 async fn problem_layer_passes_through_2xx() {
499 let app = layered_app();
500 let resp = call(&app, "/ok").await;
501 assert_eq!(resp.status(), http::StatusCode::OK);
502 let ct = resp.headers()
504 .get(header::CONTENT_TYPE)
505 .and_then(|v| v.to_str().ok())
506 .unwrap_or("");
507 assert!(!ct.contains("application/problem+json"));
508 }
509
510 #[tokio::test]
511 async fn problem_layer_passes_through_existing_problem_json() {
512 let app = layered_app();
513 let resp = call(&app, "/problem").await;
514
515 assert_eq!(resp.status(), http::StatusCode::NOT_FOUND);
516 assert_eq!(
517 resp.headers().get(header::CONTENT_TYPE).unwrap(),
518 "application/problem+json"
519 );
520
521 let body = body_string(resp).await;
523 let json: serde_json::Value = serde_json::from_str(&body).unwrap();
524 assert_eq!(json["detail"], "already a problem");
525 }
526
527 #[tokio::test]
528 async fn problem_layer_converts_axum_json_extractor_error() {
529 use axum::extract::Json;
532
533 async fn needs_json(_: Json<serde_json::Value>) -> &'static str { "ok" }
534
535 let app = Router::new()
536 .route("/json", axum::routing::post(needs_json))
537 .layer(ProblemLayer);
538
539 let resp = app
540 .oneshot(
541 http::Request::builder()
542 .method("POST")
543 .uri("/json")
544 .header("content-type", "application/json")
545 .body(Body::from("not valid json {{"))
546 .unwrap(),
547 )
548 .await
549 .unwrap();
550
551 assert!(resp.status().is_client_error());
552 assert_eq!(
553 resp.headers().get(header::CONTENT_TYPE).unwrap(),
554 "application/problem+json",
555 "axum extractor error must be converted to problem+json by ProblemLayer"
556 );
557
558 let body = body_string(resp).await;
559 let json: serde_json::Value = serde_json::from_str(&body).unwrap();
560 assert!(json["status"].as_u64().unwrap() >= 400);
561 assert!(json["title"].is_string());
562 }
563}