use axum::{ http::StatusCode, response::{IntoResponse, Response}, }; use crate::{domain::ValidationError, repository::RepositoryError}; #[derive(Debug, thiserror::Error)] pub enum AppError { #[error("bad request")] BadRequest(String), #[error("not found")] NotFound, #[error("repository error")] Repository(#[from] RepositoryError), #[error("validation error")] Validation(#[from] ValidationError), } impl IntoResponse for AppError { fn into_response(self) -> Response { match self { Self::BadRequest(error) => { return error_response(StatusCode::BAD_REQUEST, error); } Self::NotFound => { return error_response(StatusCode::NOT_FOUND, "Not found"); } Self::Validation(error) => { return error_response(StatusCode::UNPROCESSABLE_ENTITY, error.to_string()); } Self::Repository(RepositoryError::Database(error)) => { tracing::error!(%error, "Database query failed"); } Self::Repository(RepositoryError::Decode(error)) => { tracing::error!(%error, "Invalid stored data"); } } error_response(StatusCode::INTERNAL_SERVER_ERROR, "Internal server error") } } #[derive(serde::Serialize)] pub struct ErrorResponse { pub message: String, } impl ErrorResponse { pub fn new(message: impl Into) -> Self { Self { message: message.into(), } } } pub fn error_response(status_code: StatusCode, message: impl Into) -> Response { (status_code, axum::Json(ErrorResponse::new(message))).into_response() }