use axum::Json; use axum::http::StatusCode; use axum::response::{IntoResponse, Response}; use serde_json::json; #[derive(Debug, thiserror::Error)] pub enum AppError { #[error("ressource introuvable")] NotFound, #[error("{0}")] Conflict(String), #[error("{0}")] Validation(String), #[error("erreur de base de données")] Db(#[source] sqlx::Error), #[error("erreur interne")] Internal(#[source] anyhow::Error), } pub type AppResult = Result; impl AppError { pub fn status(&self) -> StatusCode { match self { Self::NotFound => StatusCode::NOT_FOUND, Self::Conflict(_) => StatusCode::CONFLICT, Self::Validation(_) => StatusCode::UNPROCESSABLE_ENTITY, Self::Db(_) | Self::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR, } } pub fn log(&self) { match self { Self::Db(e) => tracing::error!(error = %e, "database error"), Self::Internal(e) => tracing::error!(error = %e, "internal error"), _ => {} } } } impl From for AppError { fn from(e: sqlx::Error) -> Self { match &e { sqlx::Error::RowNotFound => Self::NotFound, sqlx::Error::Database(db) if db.is_unique_violation() => { Self::Conflict("cet élément existe déjà".into()) } _ => Self::Db(e), } } } impl From for AppError { fn from(e: askama::Error) -> Self { Self::Internal(e.into()) } } impl IntoResponse for AppError { fn into_response(self) -> Response { self.log(); (self.status(), Json(json!({ "error": self.to_string() }))).into_response() } }