1use axum::{
9 Json,
10 http::StatusCode,
11 response::{IntoResponse, Response},
12};
13use serde_json::json;
14
15#[derive(Debug)]
17pub struct ApiError {
18 status: StatusCode,
19 message: String,
20}
21
22impl ApiError {
23 pub fn new(status: StatusCode, message: impl Into<String>) -> Self {
24 Self {
25 status,
26 message: message.into(),
27 }
28 }
29
30 pub fn bad_request(message: impl Into<String>) -> Self {
33 Self::new(StatusCode::BAD_REQUEST, message)
34 }
35}
36
37impl std::fmt::Display for ApiError {
38 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
39 f.write_str(&self.message)
40 }
41}
42
43impl IntoResponse for ApiError {
44 fn into_response(self) -> Response {
45 if self.status.is_server_error() {
49 tracing::error!(status = %self.status, error = %self.message, "request failed");
50 return (self.status, Json(json!({ "error": "internal server error" }))).into_response();
51 }
52
53 (self.status, Json(json!({ "error": self.message }))).into_response()
54 }
55}
56
57impl From<sqlx::Error> for ApiError {
58 fn from(error: sqlx::Error) -> Self {
59 Self::new(StatusCode::INTERNAL_SERVER_ERROR, error.to_string())
60 }
61}
62
63#[cfg(test)]
64mod tests {
65 use super::*;
66 use axum::body::to_bytes;
67
68 async fn body_of(error: ApiError) -> serde_json::Value {
69 let response = error.into_response();
70 let bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap();
71 serde_json::from_slice(&bytes).unwrap()
72 }
73
74 #[tokio::test]
75 async fn client_errors_explain_themselves() {
76 let body = body_of(ApiError::bad_request("date is not a calendar date")).await;
77 assert_eq!(body["error"], "date is not a calendar date");
78 }
79
80 #[tokio::test]
81 async fn server_errors_do_not_leak_their_cause() {
82 let body = body_of(ApiError::new(StatusCode::INTERNAL_SERVER_ERROR, "relation \"users\" does not exist")).await;
83 assert_eq!(body["error"], "internal server error", "internals must not reach the client");
84 }
85
86 #[test]
87 fn the_status_survives_into_the_response() {
88 let response = ApiError::new(StatusCode::UNAUTHORIZED, "nope").into_response();
89 assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
90 }
91}