1pub use axum_problem_derive::AxumProblem;
34
35use axum::response::{IntoResponse, Response};
36use http::{header, StatusCode};
37use serde::Serialize;
38
39#[derive(Debug, Clone, Serialize)]
53pub struct Problem {
54 #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
56 pub problem_type: Option<String>,
57
58 pub title: String,
60
61 pub status: u16,
63
64 #[serde(skip_serializing_if = "Option::is_none")]
66 pub detail: Option<String>,
67
68 #[serde(skip_serializing_if = "Option::is_none")]
70 pub instance: Option<String>,
71}
72
73impl Problem {
74 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 pub fn problem_type(mut self, t: impl Into<String>) -> Self {
88 self.problem_type = Some(t.into());
89 self
90 }
91
92 pub fn title(mut self, title: impl Into<String>) -> Self {
94 self.title = title.into();
95 self
96 }
97
98 pub fn detail(mut self, detail: impl Into<String>) -> Self {
100 self.detail = Some(detail.into());
101 self
102 }
103
104 pub fn instance(mut self, instance: impl Into<String>) -> Self {
106 self.instance = Some(instance.into());
107 self
108 }
109
110 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 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
148pub 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}