diff options
Diffstat (limited to 'src/error.rs')
| -rw-r--r-- | src/error.rs | 47 |
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() } } |
