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)]
76pub struct Problem {
77 #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
79 pub problem_type: Option<String>,
80
81 pub title: String,
83
84 pub status: u16,
86
87 #[serde(skip_serializing_if = "Option::is_none")]
89 pub detail: Option<String>,
90
91 #[serde(skip_serializing_if = "Option::is_none")]
93 pub instance: Option<String>,
94}
95
96impl Problem {
97 pub fn new(status: u16) -> Self {
100 Self {
101 problem_type: None,
102 title: status_title(status).to_owned(),
103 status,
104 detail: None,
105 instance: None,
106 }
107 }
108
109 pub fn problem_type(mut self, t: impl Into<String>) -> Self {
111 self.problem_type = Some(t.into());
112 self
113 }
114
115 pub fn title(mut self, title: impl Into<String>) -> Self {
117 self.title = title.into();
118 self
119 }
120
121 pub fn detail(mut self, detail: impl Into<String>) -> Self {
123 self.detail = Some(detail.into());
124 self
125 }
126
127 pub fn instance(mut self, instance: impl Into<String>) -> Self {
129 self.instance = Some(instance.into());
130 self
131 }
132
133 pub fn bad_request() -> Self { Self::new(400) }
136 pub fn unauthorized() -> Self { Self::new(401) }
137 pub fn forbidden() -> Self { Self::new(403) }
138 pub fn not_found() -> Self { Self::new(404) }
139 pub fn method_not_allowed() -> Self { Self::new(405) }
140 pub fn conflict() -> Self { Self::new(409) }
141 pub fn unprocessable_entity() -> Self { Self::new(422) }
142 pub fn too_many_requests() -> Self { Self::new(429) }
143 pub fn internal_server_error() -> Self { Self::new(500) }
144 pub fn not_implemented() -> Self { Self::new(501) }
145 pub fn service_unavailable() -> Self { Self::new(503) }
146}
147
148impl IntoResponse for Problem {
149 fn into_response(self) -> Response {
150 let status = StatusCode::from_u16(self.status)
151 .unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
152
153 let mut serializable = self;
157 serializable.status = status.as_u16();
158
159 let body = serde_json::to_string(&serializable)
160 .unwrap_or_else(|_| r#"{"title":"Internal Server Error","status":500}"#.to_owned());
161
162 (
163 status,
164 [(header::CONTENT_TYPE, "application/problem+json")],
165 body,
166 )
167 .into_response()
168 }
169}
170
171pub fn status_title(status: u16) -> &'static str {
173 match status {
174 400 => "Bad Request",
175 401 => "Unauthorized",
176 403 => "Forbidden",
177 404 => "Not Found",
178 405 => "Method Not Allowed",
179 408 => "Request Timeout",
180 409 => "Conflict",
181 410 => "Gone",
182 415 => "Unsupported Media Type",
183 422 => "Unprocessable Entity",
184 429 => "Too Many Requests",
185 500 => "Internal Server Error",
186 501 => "Not Implemented",
187 502 => "Bad Gateway",
188 503 => "Service Unavailable",
189 504 => "Gateway Timeout",
190 _ => "Error",
191 }
192}
193
194#[derive(Clone, Copy, Default)]
215pub struct ProblemLayer;
216
217impl<S> tower_layer::Layer<S> for ProblemLayer {
218 type Service = ProblemService<S>;
219 fn layer(&self, inner: S) -> Self::Service {
220 ProblemService { inner }
221 }
222}
223
224#[derive(Clone)]
226pub struct ProblemService<S> {
227 inner: S,
228}
229
230impl<S, ReqBody> tower::Service<http::Request<ReqBody>> for ProblemService<S>
231where
232 S: tower::Service<http::Request<ReqBody>, Response = axum::response::Response>
233 + Clone
234 + Send
235 + 'static,
236 S::Future: Send + 'static,
237 ReqBody: Send + 'static,
238{
239 type Response = axum::response::Response;
240 type Error = S::Error;
241 type Future = std::pin::Pin<
242 Box<dyn std::future::Future<Output = Result<Self::Response, Self::Error>> + Send>,
243 >;
244
245 fn poll_ready(
246 &mut self,
247 cx: &mut std::task::Context<'_>,
248 ) -> std::task::Poll<Result<(), Self::Error>> {
249 self.inner.poll_ready(cx)
250 }
251
252 fn call(&mut self, req: http::Request<ReqBody>) -> Self::Future {
253 use axum::response::IntoResponse;
254 let future = self.inner.call(req);
255 Box::pin(async move {
256 let resp = future.await?;
257 let status = resp.status();
258
259 if status.is_client_error() || status.is_server_error() {
260 let already_problem = resp
261 .headers()
262 .get(http::header::CONTENT_TYPE)
263 .and_then(|v| v.to_str().ok())
264 .map(|ct| ct.contains("application/problem+json"))
265 .unwrap_or(false);
266
267 if !already_problem {
268 return Ok(Problem::new(status.as_u16()).into_response());
269 }
270 }
271
272 Ok(resp)
273 })
274 }
275}
276
277#[cfg(test)]
278mod tests {
279 use super::*;
280 use axum::body::to_bytes;
281
282 async fn body_string(resp: Response) -> String {
283 let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
284 String::from_utf8(bytes.to_vec()).unwrap()
285 }
286
287 #[tokio::test]
288 async fn problem_serializes_to_correct_json() {
289 let p = Problem::not_found().detail("order 1001 not found");
290 let resp = p.into_response();
291
292 assert_eq!(resp.status(), StatusCode::NOT_FOUND);
293 assert_eq!(
294 resp.headers().get(header::CONTENT_TYPE).unwrap(),
295 "application/problem+json"
296 );
297
298 let body = body_string(resp).await;
299 let json: serde_json::Value = serde_json::from_str(&body).unwrap();
300 assert_eq!(json["status"], 404);
301 assert_eq!(json["title"], "Not Found");
302 assert_eq!(json["detail"], "order 1001 not found");
303 }
304
305 #[tokio::test]
306 async fn problem_omits_optional_fields() {
307 let p = Problem::new(400);
308 let resp = p.into_response();
309 let body = body_string(resp).await;
310 let json: serde_json::Value = serde_json::from_str(&body).unwrap();
311 assert!(json.get("detail").is_none());
312 assert!(json.get("instance").is_none());
313 assert!(json.get("type").is_none());
314 }
315
316 #[tokio::test]
317 async fn problem_with_type_uri() {
318 let p = Problem::new(422)
319 .problem_type("https://errors.example.com/validation-failed")
320 .detail("email is required");
321 let resp = p.into_response();
322 let body = body_string(resp).await;
323 let json: serde_json::Value = serde_json::from_str(&body).unwrap();
324 assert_eq!(json["type"], "https://errors.example.com/validation-failed");
325 }
326
327 #[tokio::test]
328 async fn status_title_coverage() {
329 assert_eq!(status_title(404), "Not Found");
330 assert_eq!(status_title(500), "Internal Server Error");
331 assert_eq!(status_title(999), "Error");
332 }
333
334 use axum::{Router, routing::get, body::Body};
337 use tower::ServiceExt;
338
339 async fn handler_404() -> impl axum::response::IntoResponse {
340 (http::StatusCode::NOT_FOUND, "plain text 404")
341 }
342
343 async fn handler_200() -> impl axum::response::IntoResponse {
344 "ok"
345 }
346
347 async fn handler_problem() -> impl axum::response::IntoResponse {
348 Problem::not_found().detail("already a problem")
349 }
350
351 fn layered_app() -> Router {
352 Router::new()
353 .route("/notfound", get(handler_404))
354 .route("/ok", get(handler_200))
355 .route("/problem", get(handler_problem))
356 .layer(ProblemLayer)
357 }
358
359 async fn call(app: &Router, uri: &str) -> axum::response::Response {
360 app.clone()
361 .oneshot(
362 http::Request::builder()
363 .uri(uri)
364 .body(Body::empty())
365 .unwrap(),
366 )
367 .await
368 .unwrap()
369 }
370
371 #[tokio::test]
372 async fn problem_layer_converts_plain_404_to_problem_json() {
373 let app = layered_app();
374 let resp = call(&app, "/notfound").await;
375
376 assert_eq!(resp.status(), http::StatusCode::NOT_FOUND);
377 assert_eq!(
378 resp.headers().get(header::CONTENT_TYPE).unwrap(),
379 "application/problem+json"
380 );
381
382 let body = body_string(resp).await;
383 let json: serde_json::Value = serde_json::from_str(&body).unwrap();
384 assert_eq!(json["status"], 404);
385 assert_eq!(json["title"], "Not Found");
386 }
387
388 #[tokio::test]
389 async fn problem_layer_passes_through_2xx() {
390 let app = layered_app();
391 let resp = call(&app, "/ok").await;
392 assert_eq!(resp.status(), http::StatusCode::OK);
393 let ct = resp.headers()
395 .get(header::CONTENT_TYPE)
396 .and_then(|v| v.to_str().ok())
397 .unwrap_or("");
398 assert!(!ct.contains("application/problem+json"));
399 }
400
401 #[tokio::test]
402 async fn problem_layer_passes_through_existing_problem_json() {
403 let app = layered_app();
404 let resp = call(&app, "/problem").await;
405
406 assert_eq!(resp.status(), http::StatusCode::NOT_FOUND);
407 assert_eq!(
408 resp.headers().get(header::CONTENT_TYPE).unwrap(),
409 "application/problem+json"
410 );
411
412 let body = body_string(resp).await;
414 let json: serde_json::Value = serde_json::from_str(&body).unwrap();
415 assert_eq!(json["detail"], "already a problem");
416 }
417
418 #[tokio::test]
419 async fn problem_layer_converts_axum_json_extractor_error() {
420 use axum::extract::Json;
423
424 async fn needs_json(_: Json<serde_json::Value>) -> &'static str { "ok" }
425
426 let app = Router::new()
427 .route("/json", axum::routing::post(needs_json))
428 .layer(ProblemLayer);
429
430 let resp = app
431 .oneshot(
432 http::Request::builder()
433 .method("POST")
434 .uri("/json")
435 .header("content-type", "application/json")
436 .body(Body::from("not valid json {{"))
437 .unwrap(),
438 )
439 .await
440 .unwrap();
441
442 assert!(resp.status().is_client_error());
443 assert_eq!(
444 resp.headers().get(header::CONTENT_TYPE).unwrap(),
445 "application/problem+json",
446 "axum extractor error must be converted to problem+json by ProblemLayer"
447 );
448
449 let body = body_string(resp).await;
450 let json: serde_json::Value = serde_json::from_str(&body).unwrap();
451 assert!(json["status"].as_u64().unwrap() >= 400);
452 assert!(json["title"].is_string());
453 }
454}