error.rs (1510B)
1 use axum::http::StatusCode; 2 use axum::response::{IntoResponse, Response}; 3 4 #[derive(Debug)] 5 pub enum AppError { 6 Database(String), 7 Template(askama::Error), 8 NotFound(String), 9 Unauthorized(String), 10 } 11 12 impl std::fmt::Display for AppError { 13 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 14 match self { 15 Self::Database(e) => write!(f, "Database error: {e}"), 16 Self::Template(e) => write!(f, "Template error: {e}"), 17 Self::NotFound(e) => write!(f, "Not found: {e}"), 18 Self::Unauthorized(e) => write!(f, "Unauthorized: {e}"), 19 } 20 } 21 } 22 23 impl std::error::Error for AppError {} 24 25 impl From<askama::Error> for AppError { 26 fn from(e: askama::Error) -> Self { 27 Self::Template(e) 28 } 29 } 30 31 impl IntoResponse for AppError { 32 fn into_response(self) -> Response { 33 let (status, message) = match &self { 34 AppError::Database(e) => { 35 eprintln!("Database error: {}", e); 36 (StatusCode::INTERNAL_SERVER_ERROR, format!("Database error: {}", e)) 37 } 38 AppError::Template(e) => { 39 eprintln!("Template error: {}", e); 40 (StatusCode::INTERNAL_SERVER_ERROR, format!("Template error: {}", e)) 41 } 42 AppError::NotFound(msg) => (StatusCode::NOT_FOUND, msg.clone()), 43 AppError::Unauthorized(msg) => (StatusCode::UNAUTHORIZED, msg.clone()), 44 }; 45 46 (status, message).into_response() 47 } 48 }