Skip to main content

axum_problem/
lib.rs

1//! RFC 9457 problem details for axum.
2//!
3//! # Quick start
4//!
5//! ```rust,no_run
6//! use axum::{Router, routing::get, extract::Path};
7//! use axum_problem::{AxumProblem, Problem};
8//! use thiserror::Error;
9//!
10//! #[derive(Debug, Error, AxumProblem)]
11//! pub enum ApiError {
12//!     #[error("order {id} not found")]
13//!     #[problem(status = 404)]
14//!     NotFound { id: i64 },
15//!
16//!     #[error("unauthorized")]
17//!     #[problem(status = 401)]
18//!     Unauthorized,
19//!
20//!     #[error("database error: {0}")]
21//!     #[problem(status = 500, mask)]
22//!     Database(String),
23//! }
24//!
25//! async fn get_order(Path(id): Path<i64>) -> Result<String, ApiError> {
26//!     Err(ApiError::NotFound { id })
27//! }
28//! ```
29//!
30//! The `mask` attribute hides the error detail from the HTTP response (preventing
31//! internal details leaking to clients) and logs the full error via `tracing::error!`.
32
33pub use axum_problem_derive::AxumProblem;
34
35use axum::response::{IntoResponse, Response};
36use http::{header, StatusCode};
37use serde::Serialize;
38
39/// An RFC 9457 problem details response.
40///
41/// Serializes to `application/problem+json` with the correct HTTP status code.
42///
43/// # Manual construction
44///
45/// ```rust
46/// use axum_problem::Problem;
47///
48/// let p = Problem::new(404)
49///     .title("Order Not Found")
50///     .detail("Order 1001 does not exist");
51/// ```
52#[derive(Debug, Clone, Serialize)]
53pub struct Problem {
54    /// URI reference identifying the problem type. Defaults to `"about:blank"`.
55    #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
56    pub problem_type: Option<String>,
57
58    /// Short human-readable summary of the problem type.
59    pub title: String,
60
61    /// HTTP status code.
62    pub status: u16,
63
64    /// Human-readable explanation specific to this occurrence.
65    #[serde(skip_serializing_if = "Option::is_none")]
66    pub detail: Option<String>,
67
68    /// URI identifying the specific occurrence of this problem.
69    #[serde(skip_serializing_if = "Option::is_none")]
70    pub instance: Option<String>,
71}
72
73impl Problem {
74    /// Create a new problem for the given HTTP status code.
75    /// The title is set automatically from the status code.
76    pub fn new(status: u16) -> Self {
77        Self {
78            problem_type: None,
79            title: status_title(status).to_owned(),
80            status,
81            detail: None,
82            instance: None,
83        }
84    }
85
86    /// Set the problem type URI (defaults to `"about:blank"` in the response).
87    pub fn problem_type(mut self, t: impl Into<String>) -> Self {
88        self.problem_type = Some(t.into());
89        self
90    }
91
92    /// Override the title.
93    pub fn title(mut self, title: impl Into<String>) -> Self {
94        self.title = title.into();
95        self
96    }
97
98    /// Add a human-readable explanation for this specific occurrence.
99    pub fn detail(mut self, detail: impl Into<String>) -> Self {
100        self.detail = Some(detail.into());
101        self
102    }
103
104    /// Add a URI identifying this specific occurrence.
105    pub fn instance(mut self, instance: impl Into<String>) -> Self {
106        self.instance = Some(instance.into());
107        self
108    }
109
110    // ── Convenience constructors ──────────────────────────────────────────────
111
112    pub fn bad_request() -> Self { Self::new(400) }
113    pub fn unauthorized() -> Self { Self::new(401) }
114    pub fn forbidden() -> Self { Self::new(403) }
115    pub fn not_found() -> Self { Self::new(404) }
116    pub fn method_not_allowed() -> Self { Self::new(405) }
117    pub fn conflict() -> Self { Self::new(409) }
118    pub fn unprocessable_entity() -> Self { Self::new(422) }
119    pub fn too_many_requests() -> Self { Self::new(429) }
120    pub fn internal_server_error() -> Self { Self::new(500) }
121    pub fn not_implemented() -> Self { Self::new(501) }
122    pub fn service_unavailable() -> Self { Self::new(503) }
123}
124
125impl IntoResponse for Problem {
126    fn into_response(self) -> Response {
127        let status = StatusCode::from_u16(self.status)
128            .unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
129
130        // Sync the JSON `status` field with the actual HTTP status line.
131        // If the caller passed an invalid code (e.g. 0), both the HTTP status
132        // and the JSON body must agree — returning 500 in both.
133        let mut serializable = self;
134        serializable.status = status.as_u16();
135
136        let body = serde_json::to_string(&serializable)
137            .unwrap_or_else(|_| r#"{"title":"Internal Server Error","status":500}"#.to_owned());
138
139        (
140            status,
141            [(header::CONTENT_TYPE, "application/problem+json")],
142            body,
143        )
144            .into_response()
145    }
146}
147
148/// Returns a short title for common HTTP status codes.
149pub fn status_title(status: u16) -> &'static str {
150    match status {
151        400 => "Bad Request",
152        401 => "Unauthorized",
153        403 => "Forbidden",
154        404 => "Not Found",
155        405 => "Method Not Allowed",
156        408 => "Request Timeout",
157        409 => "Conflict",
158        410 => "Gone",
159        415 => "Unsupported Media Type",
160        422 => "Unprocessable Entity",
161        429 => "Too Many Requests",
162        500 => "Internal Server Error",
163        501 => "Not Implemented",
164        502 => "Bad Gateway",
165        503 => "Service Unavailable",
166        504 => "Gateway Timeout",
167        _ => "Error",
168    }
169}
170
171#[cfg(test)]
172mod tests {
173    use super::*;
174    use axum::body::to_bytes;
175
176    async fn body_string(resp: Response) -> String {
177        let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
178        String::from_utf8(bytes.to_vec()).unwrap()
179    }
180
181    #[tokio::test]
182    async fn problem_serializes_to_correct_json() {
183        let p = Problem::not_found().detail("order 1001 not found");
184        let resp = p.into_response();
185
186        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
187        assert_eq!(
188            resp.headers().get(header::CONTENT_TYPE).unwrap(),
189            "application/problem+json"
190        );
191
192        let body = body_string(resp).await;
193        let json: serde_json::Value = serde_json::from_str(&body).unwrap();
194        assert_eq!(json["status"], 404);
195        assert_eq!(json["title"], "Not Found");
196        assert_eq!(json["detail"], "order 1001 not found");
197    }
198
199    #[tokio::test]
200    async fn problem_omits_optional_fields() {
201        let p = Problem::new(400);
202        let resp = p.into_response();
203        let body = body_string(resp).await;
204        let json: serde_json::Value = serde_json::from_str(&body).unwrap();
205        assert!(json.get("detail").is_none());
206        assert!(json.get("instance").is_none());
207        assert!(json.get("type").is_none());
208    }
209
210    #[tokio::test]
211    async fn problem_with_type_uri() {
212        let p = Problem::new(422)
213            .problem_type("https://errors.example.com/validation-failed")
214            .detail("email is required");
215        let resp = p.into_response();
216        let body = body_string(resp).await;
217        let json: serde_json::Value = serde_json::from_str(&body).unwrap();
218        assert_eq!(json["type"], "https://errors.example.com/validation-failed");
219    }
220
221    #[tokio::test]
222    async fn status_title_coverage() {
223        assert_eq!(status_title(404), "Not Found");
224        assert_eq!(status_title(500), "Internal Server Error");
225        assert_eq!(status_title(999), "Error");
226    }
227}