summaryrefslogtreecommitdiff
path: root/src/error.rs
diff options
context:
space:
mode:
authorbatsumaru <>2026-10-16 15:17:17 +0900
committerbatsumaru <>2026-10-16 15:17:17 +0900
commitb49bb08c7a77fe4b29cf4ed0504c2f1c32a025e3 (patch)
treeea763ca8cb858768e8ac8179f0bd6e32978541b7 /src/error.rs
parentad9a134daec1f73940e8deaeb6c2a481ce9d6520 (diff)
Update error responses
Diffstat (limited to 'src/error.rs')
-rw-r--r--src/error.rs47
1 files changed, 39 insertions, 8 deletions
diff --git a/src/error.rs b/src/error.rs
index d8aaf18..232d588 100644
--- a/src/error.rs
+++ b/src/error.rs
@@ -1,13 +1,18 @@
use axum::{
+ Json,
+ extract::rejection::{JsonRejection, PathRejection, QueryRejection},
http::StatusCode,
response::{IntoResponse, Response},
};
+use serde_json::json;
pub enum AppError {
- BadRequest,
+ BadRequest(&'static str),
Conflict,
Database(sqlx::Error),
+ MethodNotAllowed,
NotFound,
+ Rejection(StatusCode, String),
}
impl From<sqlx::Error> for AppError {
@@ -20,17 +25,43 @@ impl From<sqlx::Error> for AppError {
}
}
+impl From<JsonRejection> for AppError {
+ fn from(rejection: JsonRejection) -> Self {
+ AppError::Rejection(rejection.status(), rejection.body_text())
+ }
+}
+
+impl From<QueryRejection> for AppError {
+ fn from(rejection: QueryRejection) -> Self {
+ AppError::Rejection(rejection.status(), rejection.body_text())
+ }
+}
+
+impl From<PathRejection> for AppError {
+ fn from(rejection: PathRejection) -> Self {
+ AppError::Rejection(rejection.status(), rejection.body_text())
+ }
+}
+
impl IntoResponse for AppError {
fn into_response(self) -> Response {
- match self {
- AppError::BadRequest => StatusCode::BAD_REQUEST,
- AppError::Conflict => StatusCode::CONFLICT,
+ let (status, message) = match self {
+ AppError::BadRequest(message) => (StatusCode::BAD_REQUEST, message.to_owned()),
+ AppError::Conflict => (StatusCode::CONFLICT, "already exists".to_owned()),
AppError::Database(e) => {
tracing::error!("database error: {e}");
- StatusCode::INTERNAL_SERVER_ERROR
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ "internal server error".to_owned(),
+ )
}
- AppError::NotFound => StatusCode::NOT_FOUND,
- }
- .into_response()
+ AppError::MethodNotAllowed => (
+ StatusCode::METHOD_NOT_ALLOWED,
+ "method not allowed".to_owned(),
+ ),
+ AppError::NotFound => (StatusCode::NOT_FOUND, "not found".to_owned()),
+ AppError::Rejection(status, message) => (status, message),
+ };
+ (status, Json(json!({ "error": message }))).into_response()
}
}